Search code examples
swiftxcodeuser-interfaceautolayout

How to programmatically pin a UIImageView


I read the documentation, but I just can't figure out what exactly is needed in my simple case. The element is constantly jumping. I need just that. I would be grateful for articles and so on. For a deeper understanding of this

enter image description here

class MyViewController : UIViewController {
    override func loadView() {
    
        let view = UIView()
        view.backgroundColor = .white
        
        let imageView = UIImageView()
        
        view.addSubview(imageView)
       
        
        self.view = view
    }
}

Solution

  • imageView.translatesAutoresizingMaskIntoConstraints = false
    
    // Apply constraint
    
    NSLayoutConstraint.activate([
        imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
        imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
        imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
        imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1)
    ])