【发布时间】:2015-08-13 18:31:01
【问题描述】:
我已经竭尽全力寻找这个问题的答案。在我正在创建的应用程序中,用户将单击 addImage 按钮,然后从 ImagePickerController 的照片库(或相机)中选择一个图像,然后将所选图像传递到第二个视图控制器上的图像视图。
当图像视图与 addImage 按钮位于同一视图上时,我知道如何执行此操作,但不知道如何正确使用 segue 将图像传递到第二个视图。希望有人可以帮我解决这个问题。
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var newImage = UIImage(named: "")
@IBOutlet var imageView: UIImageView!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addImage(sender: UIButton) {
var alert = UIAlertController(title: "Please Get An Image", message: "Choose from below", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Camera", style: .Default, handler: {(action) -> Void in
self.imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(self.imagePicker, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Photo Library", style: .Default, handler: {(action) -> Void in
self.imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(self.imagePicker, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: {(action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
newImage = image
//not sure about this next line here...
performSegueWithIdentifier("VC2", sender: self)
self.dismissViewControllerAnimated(true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var secondViewController: VC2 = segue.destinationViewController as! VC2
secondViewController.imageView.image = newImage
}
}// end of app
【问题讨论】:
-
当您尝试设置 newImage 时,您确定 VC2 上的 UIImageView 已经实例化了吗?
-
我不确定。你能解释一下我会怎么做吗?我为 VC2 上的图像视图创建了一个 IBOutlet。我还需要做其他步骤吗?在 View Did Load 中,我设置了 imageView.Image = holderImage ,它假设保存在第一个 View 中选择的图像。
-
正如answer 建议的那样,您可以在 prepareForSegue 函数上设置断点并检查您的视图控制器是否已正确实例化
标签: ios swift xcode6 uiimagepickercontroller uistoryboardsegue