Search code examples
iosxcodeswiftuiimageviewuiimage

How do you create a UIImage View Programmatically - Swift


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


Solution

  • 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)