Layout Anchors is the most convenient way to set constraints programmatically.
Say you want to set 5:1 aspect ratio for your button then you should use:
button.heightAnchor.constraint(equalTo: button.widthAnchor, multiplier: 1.0/5.0).isActive = true
Here's the full code:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .custom)
button.setTitle("Login", for: .normal)
button.backgroundColor = UIColor.darkGray
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
let margins = view.layoutMarginsGuide
button.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20.0).isActive = true
button.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -20.0).isActive = true
button.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -20.0).isActive = true
button.heightAnchor.constraint(equalTo: button.widthAnchor, multiplier: 1.0/5.0).isActive = true
}
}
Here're results achieved with code written above. You can see that button keeps its 5:1 aspect ratio across various devices:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…