Search code examples
iosswiftswift3uiimagepickercontrollerphoto

use image picker to save photos to 2 different image view (swift3)


I want the user to take 2 different photos using 2 different imageviews and buttons (a left and right side). I know how to do this with using imagepicker Delegate but not with 2 different imageviews. Both imageviews will have different photos and use a different button to take the photo. Basically the left and right sides have nothing to do with each other. simulator pic

code

    import UIKit

class _vc: UIViewController {

@IBOutlet var leftImage: UIImageView!
@IBOutlet var rightImage: UIImageView!


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

@IBAction func takePhotoLeft(_ sender: Any) {
}
@IBAction func takePhotoRgith(_ sender: Any) {
}}

Solution

  • Instead of setting tag the simple option is to make one instance property of type UIImageView name currentImageView in your ViewController and then in your left and right Button action set that currentImageView with leftImage and rightImage. After that in didFinishPickingMediaWithInfo set the selected image to this currentImageView.

    var currentImageView: UIImageView?
    
    @IBAction func takePhotoLeft(_ sender: Any) {
        self.currentImageView = self.leftImage
        //ImagePicker code
    }
    
    @IBAction func takePhotoRgith(_ sender: Any) {
        self.currentImageView = self.rightImage
        //ImagePicker code
    }
    

    Now in your didFinishPickingMediaWithInfo method simply set image to this currentImageView.

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        self.currentImageView?.image = image
        self.dismiss(animated: true)
    }