捕获两个图像并将其显示到两个UIImageView

时间:2019-05-17 13:51:18

标签: ios swift

我打算在同一视图控制器上拍摄2张个人资料照片,两者均具有各自独立的按钮和图像视图。

我正在为此使用Swift 4版本。

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

  @IBOutlet weak var profileA: UIImageView!
  @IBOutlet weak var profileB: UIImageView!

  var profileAPicker: UIImagePickerController!
  var profileBPicker: UIImagePickerController!

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    profileAPicker.dismiss(animated: true, completion: nil)
    profileA.image = info[.originalImage] as? UIImage

    profileBPicker.dismiss(animated: true, completion: nil)
    profileB.image = info[.originalImage] as? UIImage
  }

  @IBAction func takeProfileA(_ sender: Any) {

    profileAPicker = UIImagePickerController()
    profileAPicker.delegate = self
    profileAPicker.sourceType = .camera

    present(profileAPicker, animated: true , completion: nil)
  }

  @IBAction func takeProfileB(_ sender: Any) {

    profileBPicker = UIImagePickerController()
    profileBPicker.delegate = self
    profileBPicker.sourceType = .camera

    present(profileBPicker, animated: true , completion: nil)
  }

}

当我为个人资料A拍照时可以使用,但是当我为个人资料B拍照时可以停止使用。

2 个答案:

答案 0 :(得分:0)

如果我理解正确的问题... 似乎可以通过以下方式解决此问题:

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    picker.dismiss(animated: true, completion: nil)
    if picker == profileAPicker {
        profileA.image = info[.originalImage] as? UIImage
    }
    else if picker == profileBPicker {
        profileB.image = info[.originalImage] as? UIImage
    }
}

答案 1 :(得分:0)

您的方法不正确。您的代码在两个隐式未包装的可选选项上调用dismiss,而与是否已设置属性无关。

您不需要任何图像选择器属性。只需跟踪要更新的图像视图即可。

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
  @IBOutlet weak var profileA: UIImageView!
  @IBOutlet weak var profileB: UIImageView!

  var currentImageView: UIImageView?

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    picker.dismiss(animated: true, completion: nil)

    currentImageView?.image = info[.originalImage] as? UIImage
  }

  @IBAction func takeProfileA(_ sender: Any) {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .camera
    currentImageView = profileA

    present(picker, animated: true , completion: nil)
  }

  @IBAction func takeProfileB(_ sender: Any) {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .camera
    currentImageView = profileB

    present(picker, animated: true , completion: nil)
  }

}