Friday, December 5, 2014

presentPopoverFromRect - Show a photo from the photo album to a popover with an iPad

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: UIButton) {

    }

3. Add delegates

class ViewController: UIViewControllerUINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPopoverControllerDelegate {

4. Complete Code:


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPopoverControllerDelegate {

    @IBOutlet weak var picture: UIImageView!
    
    var myPopOverController : UIPopoverController!
    
    @IBAction func photoAlbum(sender: UIButton) {
        var myImagePickerController = UIImagePickerController()
        myImagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        myImagePickerController.delegate = self
        
        myPopOverController = UIPopoverController(contentViewController: myImagePickerController)
        
        myPopOverController.presentPopoverFromRect(sender.frame, inView: view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        let myImage = info[UIImagePickerControllerOriginalImage] as UIImage
        self.picture.image = myImage
        myPopOverController.dismissPopoverAnimated(true)

    }

1 comment:

  1. Thank you so much! This is very helpful and the code is so efficient. I was looking for a simple way to show photos using a popover in iOS7 and iOS8 on iPad. Thanks for taking the time to offer your expertise. Appreciate it. Cheers!

    ReplyDelete