如何拍照或挑选图像并传递给 VC

How to take picture or pick image and Pass to a VC

我正在尝试使用 UIImagePickerControllerUIImage 传递给另一个 ViewController。用户拍一张照片并立即将其传递给 ViewController 或 select 照片库中的图像然后传递它。

我尝试了以下代码但没有成功。

@IBAction func okButtonTapped(sender: AnyObject) {

  let imageFromSource = UIImagePickerController()
  imageFromSource.delegate = self
  imageFromSource.allowsEditing = false

  imageFromSource.sourceType = .PhotoLibrary

  presentViewController(imageFromSource, animated: true, completion: nil)

}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

  let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage

  dismissViewControllerAnimated(true, completion: {})

  let storyboard = UIStoryboard(name: "Main", bundle: nil)
  let sp = storyboard.instantiateViewControllerWithIdentifier("photoReady") as! photoReadyScreen

  sp.photoReadyImage.image = selectedImage

  presentViewController(sp, animated: true, completion: nil)

}

看来你的 photoReadyImageUIImageView 的出口。如果是这样,你看不到你的图像,因为当你实例化你的控制器插座时尚未初始化(= nil)。

要实现您想要的效果,您需要向 photoReadyScreen 控制器添加变量:

class photoReadyScreen {
...
var pickedPhoto: UIImage?
...
override func viewDidLoad() {
  super.viewDidLoad()
  photoReadyImage.image = pickedPhoto
...

并将 sp.photoReadyImage.image = selectedImage 行替换为 sp.pickedImage = image

同时考虑使用 self.storyboard 而不是创建新的。如果您的项目中只有一个故事板,则无需创建新的 - 您已经有了一个。