How to add constraints programmatically using Swift

前端 未结 17 1418
逝去的感伤
逝去的感伤 2020-11-21 23:07

I\'m trying to figure this out since last week without going any step further. Ok, so I need to apply some constraints programmatically

17条回答
  •  野性不改
    2020-11-21 23:38

    Auto layout is realized by applying constraints on images. Use NSLayoutConstraint. It is possible to implement an ideal and beautiful design on all devices. Please try the code below.

    import UIKit
    
    class ViewController: UIViewController {
    
    override func viewDidLoad() {
    super.viewDidLoad()
    
    let myImageView:UIImageView = UIImageView()
    myImageView.backgroundColor = UIColor.red
    myImageView.image = UIImage(named:"sample_dog")!
    myImageView.translatesAutoresizingMaskIntoConstraints = false
    myImageView.layer.borderColor = UIColor.red.cgColor
    myImageView.layer.borderWidth = 10
    self.view.addSubview(myImageView)
            
    view.removeConstraints(view.constraints)
    
    
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .top,
    relatedBy: .equal,
    toItem: view,
    attribute: .top,
    multiplier: 1,
    constant:100)
        
    )
    
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .centerX,
    relatedBy: .equal,
    toItem: view,
    attribute: .centerX,
    multiplier: 1,
    constant:0)
    )
        
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .height,
    relatedBy: .equal,
    toItem: view,
    attribute: .width,
    multiplier: 0.5,
    constant:40))
        
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .width,
    relatedBy: .equal,
    toItem: view,
    attribute: .width,
    multiplier: 0.5,
    constant:40))
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    }
    

提交回复
热议问题