user7459574
user7459574

Reputation:

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) {
}}

Upvotes: 1

Views: 649

Answers (2)

Nirav D
Nirav D

Reputation: 72410

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)
}

Upvotes: 1

creeperspeak
creeperspeak

Reputation: 5523

A quick way to do it would be to set a variable on your viewController to keep track of which button was pressed most recently. You could even use something as simple as an Int, like var imagePickerButton: Int = 0, and assign the numbers to the buttons however you like. I like to use the tag attribute so I don't have to think about it. If you do that, in your button action, you can say self.imagePickerButton = sender.tag before doing your imagePicker launch code.

Then, in your didFinishPicking... method you can use switch or if/else to decide which imageView to populate, like

switch self.imagePickerButton {
case 0:
    leftImageView.image = image
case 1:
    rightImageView.image = image
etc.
}

There are tons of ways you could handle this, but this is a very easy, quick one.

Upvotes: 0

Related Questions