How do you create a UIImage View Programmatically - Swift

alex picture alex · Oct 26, 2014 · Viewed 231.8k times · Source

I'm trying to create a UIImage View programmatically, I have a new view and I tried doing this

let imageName = "yourImage.png"
yourview.backgroundColor = UIColor.colorWithPatternImage(UIImage(named:imageName))

this did not work because I don't know what this should be yourview in the second line.

Question: How do I make a UIImageView appear on the screen by coding it instead of doing it in the storyboard

Answer

Nate Cook picture Nate Cook · Oct 26, 2014

First you create a UIImage from your image file, then create a UIImageView from that:

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

Finally you'll need to give imageView a frame and add it your view for it to be visible:

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