Search code examples
iosswiftuiimageviewuiimage

Programmatically loading images with Swift


I am trying to load and display images (UIImage with Swift 3) dynamically but I seem to be missing something (it's not working!) probably simple.

I am using UILabels for text descriptions and when images exist to replace the descriptions I want to load and display them. What I have so far is:

When images are found to exist, connect the images with UIImage items:

var rb1image: UIImage = UIImage(named: image1)!
var rb2image: UIImage = UIImage(named: image2)!

Connect the UIImage items with UIImageView items:

var rb1img = UIImageView(image: rb1image)
var rb2img = UIImageView(image: rb2image)

Position and size the UIImageView items using the UILabel positions and image sizes:

rb1img.frame = CGRect(x: rbanslabel1.frame.origin.x, y: rbanslabel1.frame.origin.y, width: (rb1img.image?.size.width)!, height: (rb1img.image?.size.height)!)
rb2img.frame = CGRect(x: rbanslabel2.frame.origin.x, y: rbanslabel1.frame.origin.y, width: (rb1img.image?.size.width)!, height: (rb1img.image?.size.height)!)

Labels display just fine but the images aren't being displayed. I am expecting the images to appear where the labels are.

Any hints as to what I am missing? Thanks in advance :-)

--- Added full code listing ---

The full code is:

if exists(image1) {            
    var rb1image: UIImage = UIImage(named: image1)!
    var rb2image: UIImage = UIImage(named: image2)!
    var rb1img = UIImageView(image: rb1image)
    var rb2img = UIImageView(image: rb2image)            
    rb1img.frame = CGRect(x: rbanslabel1.frame.origin.x, y: rbanslabel1.frame.origin.y, width: (rb1img.image?.size.width)!, height: (rb1img.image?.size.height)!)
    rb2img.frame = CGRect(x: rbanslabel2.frame.origin.x, y: rbanslabel1.frame.origin.y, width: (rb1img.image?.size.width)!, height: (rb1img.image?.size.height)!)

I must have been tired last night because today in the sidebar I saw this: How do you create a UIImage View Programmatically - Swift.

I was missing:

view.addSubview(rb1img)
view.addSubview(rb2img)

Solution

  • I was missing:

    view.addSubview(rb1img)
    view.addSubview(rb2img)
    

    I found the answer in the response to a different question: How do you create a UIImage View Programmatically - Swift.

    Note: I have posted the solution, which I previously added as an edit to the question, because it was showing as unanswered.