Edit ViewController.swift as below:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imageView : UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRectMake(70, 100, 200, 20))
button.setTitle("Pick a Photo", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
button.addTarget(self, action: "photoAlbum:", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
imageView = UIImageView(frame: CGRectMake(50, 150, 200, 200))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
view.addSubview(imageView)
}
func photoAlbum(sender: UIButton) {
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
self.presentViewController(pickerController, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let pictureSelected = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = pictureSelected
picker.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Original Post (November 17, 2014):
1. Drag a UIImageView and Button to the storyboard.
Adjust the view mode of UIImageView to Aspect Fit
2. Control-drag to create:
@IBOutlet weak var picture: UIImageView!
@IBAction func photoAlbum(sender: AnyObject) {
}
3. Add delegates
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
4. Complete Code:
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var picture: UIImageView!
@IBAction func photoAlbum(sender: AnyObject) {
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) {
var pickerController = UIImagePickerController()
pickerController.delegate = self
self.presentViewController(pickerController, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let pictureSelected = info[UIImagePickerControllerOriginalImage] as UIImage
self.picture.image = pictureSelected
picker.dismissViewControllerAnimated(true, completion: nil)
}
No comments:
Post a Comment