2

I am very new to swift and cant figure out how to programmatically change the picture in a UIImageView. i have tried this so far:

if let image = UIImage(named: "mouse.jpg") {
    imageView.image = image
    print("image set")
}

but it causes the found nil while unwrapping an optional fatal exception.

mouse.jpg is in the same folder as the swift file and can be set as the image views image in the inspector in Xcode.

wrapping the code in another if like this:

if let iv = imageView{
    if let image = UIImage(named: "mouse.jpg"){
        iv.image = image
    }
}

fixes the nil error but does not change the picture at all from what was set in the storyboard.

any ideas would be helpful

Blake
  • 151
  • 2
  • 11
  • 6
    This code can only crash if `imageView` is `nil`. Check the connection in IB. – vadian Apr 18 '17 at 20:31
  • I reopened since you have updated the question to something very different. Have you verified that the line `iv.image = image` is being called? It still sounds like your outlet isn't connected. – rmaddy Apr 18 '17 at 20:50
  • yeah sorry i didnt ask the question very well at first. I have a print right under this line that prints when this code is called so yes im pretty sure it gets called – Blake Apr 18 '17 at 21:02
  • Even if the IBOutlet is connected correctly, this could still result in a crash if you try to assign the image before the outlet has been assigned by the storyboard. Make sure you are setting the image *after* the view has loaded, such as inside `viewDidLoad`. – dalton_c Apr 18 '17 at 21:58
  • @Blake in case you are not using storyboards, you will have to programmatically add the ImageView to the parent view and initialize it via the init method. – joaofs Apr 18 '17 at 22:10
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Mar 19 '18 at 06:06

1 Answers1

7

If this code inside if executes it looks like it may rather be a problem with your reference to imageView rather than the image itself as the condition here requires UIImage to initialize properly. I guess you are storing reference to the imageView using implicitly unwrapped optional like: var imageView: UIImageView!.

If you are using @IBOutlet have you checked if it's connected properly? Are you sure you have an actual instance of UIImageView before setting the image property?

Mr. Hedgehog
  • 966
  • 4
  • 13
  • 1
    This. For clarity, click on the "two circle" (show assistance editor) on the upper right of xcode, and have both your storyboard and the associated view controller open. Ctrl+drag from the imageView in your storyboard to the view controller and create the appropriate outlet for your imageView. Now, when you reference it in the code here it shouldn't even be nil. – Meshach Apr 18 '17 at 21:28