简体   繁体   中英

Why am I getting the error “fatal error: found nil while unwrapping optional value”?

Currently I have 4 small imageViews which present images taken from a camera. When I click on one of these images, I want it to take me to a separate modal view controller where the screen fills the whole VC. The code below shows that I have attached 4 textless buttons to my smaller imageViews, which when clicked I am hoping to take me to a separate modal view controller I have set up.

imageView5 is the imageView I have set up on my modal VC and "bigImager" is the segue identifier.

Let me know if you have any thoughts?

@IBAction func bigImage1(sender: AnyObject) {
    if imageView1.image != nil {

    print(sender.tag)
    }
}

@IBAction func bigImage2(sender: AnyObject) {
    if imageView2.image != nil {

   self.performSegueWithIdentifier("bigImager", sender: self)
    }
}

@IBAction func bigImage3(sender: AnyObject) {
    if imageView3.image != nil {

    self.performSegueWithIdentifier("bigImager", sender: self)
    }
}

@IBAction func bigImage4(sender: AnyObject) {
    if imageView4.image != nil {

   self.performSegueWithIdentifier("bigImager", sender: self)
    }
}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "bigImager" {
       let dvc: ImageViewController = segue.destinationViewController as! ImageViewController
        dvc.imageView5.image = imageViewArray[sender!.tag].image

    }
}

检查prepareForSegue的发送者是否为nil

Is imageView5 an implicitly unwrapped optional? If so, it may have not been created yet.

I suggest adding an var image: UIImage? property to ImageViewController . Then you can set it like so:

if let dvc = segue.destinationViewController as? ImageViewController {
    dvc.image = imageViewArray[sender!.tag].image
}

Inside of ImageViewController , you can set the image at the appropriate time. One approach would be to use didSet :

class ImageViewController: UIViewController {
    var image: UIImage? {
        didSet {
            updateViews()
        }
    }

    var imageView5: UIImageView! {
        didSet {
            updateViews()
        }
    }

    func updateViews() {
        if imageView5 != nil {
            imageView5.image = image
        }
    }
}

显然我看不到您为imageViewArray设置值的任何地方,请确保正确设置此数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM