Joakim Sjöstedt
Joakim Sjöstedt

Reputation: 958

How do I directly assign an image to a UIImageView?

I have an imageView with an outlet called humanEyesUIIV and now simply want to add an image programmatically. I use the following code:

humanEyesArray = [
        UIImage(named: "humanEyes0")!
        ]

   humanEyesUIIV.image? = humanEyesArray[0]

No error shows and the simulator runs fine, but the picture doesn't show up for some reason. I have looked at this thread and the code there works fine:

How do you create a UIImage View Programmatically - Swift

let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)

imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(imageView)

The problem is just that I want to insert the imageView in the UI and handle its constraints and so on there, then simple add the image programatically. Any ideas what's wrong with my code?

Upvotes: 0

Views: 713

Answers (2)

Joakim Sjöstedt
Joakim Sjöstedt

Reputation: 958

OK, solved it now by removing the question mark :) So, instead of:

   humanEyesUIIV.image? = humanEyesArray[0]

I now have:

   humanEyesUIIV.image = humanEyesArray[0]

That's it! :) Thanks for helping me out :)

Upvotes: 0

Fattie
Fattie

Reputation: 12278

To get you going, just put a simple UIImageView in the scene in storyboard. Make it large, ensure you have four constraints, and put in an image of a cat or something.

Now add an @IBOutlet var test UIImageView! and connect it.

Next add some code like test.alpha = 0.1 just to absolutely check you are OK so far.

Finally, just go test.image = .. your image.

This will allow you to test one problem at a time.

Upvotes: 1

Related Questions