Search code examples
iosswiftuiimageviewuikitconstraints

iOS: Programmatically align UIImageView to bottom using anchors


I am trying to create an UIImageView programmatically (so no storyboard/UI editor), and align it using anchor constraints. The UIImageView should be aligned to the bottom and be scaled to fit the bottom area (like a full-width footer), but maintain aspect ratio, kind of like what is available in the Storyboard editor?

enter image description here

My current code in viewDidLoad() looks like this, but no matter what I do, the image is displayed at the top and it seems the ImageView (not the image) fills the entire height of the parent view.

// Create and add image view
let imgView = UIImageView(image : UIImage(named : "Images/main_bottom.png"))
imgView.translatesAutoresizingMaskIntoConstraints = false
imgView.contentMode = .scaleAspectFit

view.addSubview(imgView)


// Align image view
let margins = view.safeAreaLayoutGuide

NSLayoutConstraint.activate([
    imgView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
    imgView.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
    imgView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])

Solution

  • I was able to find a solution using the comments above and further experiments, by computing and setting the height anchor from the image ratio.

    // Compute image ratio
    let ratio = imgView.intrinsicContentSize.height / imgView.intrinsicContentSize.width
    
    // Set height anchor as a computed value of the (auto-scaled) width, and the image ratio
    NSLayoutConstraint.activate([
       // ...other contraints go here still...
       imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor, multiplier: ratio)
    ])