将图像从一个视图控制器传递到另一个控制器给出nil

时间:2018-03-06 17:44:12

标签: swift uiviewcontroller segue

我正在尝试将图像发送到预览控制器,如下所示。我的问题是预览控制器 newImagenil

以下是代码:

FirstViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("In here")
    if segue.identifier == "showImage" {

        let secondViewController = self.storyboard!.instantiateViewController(withIdentifier: "showImage") as! showImageController

        secondViewController.newImage =  UIImage(named: imageArray[0])

    }
}

PreviewController

@IBOutlet weak var imageHolder: UIImageView!
var newImage: UIImage!

override func viewDidLoad() {
    super.viewDidLoad()
    imageHolder.image = newImage
    // Do any additional setup after loading the view.
}

2 个答案:

答案 0 :(得分:2)

您应该使用segue.destination而不是创建一个新的

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

   print("In here")

   if segue.identifier == "showImage" {

        let next = segue.destination as! showImageController

        next.newImage =  UIImage(named: imageArray[0])

    }

 }

答案 1 :(得分:0)

instantiateViewController调用viewDidLoad(),因此在调用图像时不会设置图像。将代码移动到viewWillAppear(),它将起作用