How can I set aspect ratio constraints programmatically in iOS?
Like this. Try once.
[self.yourview setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.yourview addConstraint:[NSLayoutConstraint
constraintWithItem:self.yourview
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.yourview
attribute:NSLayoutAttributeWidth
multiplier:(self.yourview.frame.size.height / self.yourview.frame.size.width)
constant:0]];
or in the place of (self.yourview.frame.size.height / self.yourview.frame.size.width)
you can use any float value.
Thanks.
Swift 3.0 -
self.yourview!.translatesAutoresizingMaskIntoConstraints = false
self.yourview!.addConstraint(NSLayoutConstraint(item: self.yourview!,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.yourview!,
attribute: NSLayoutAttribute.width,
multiplier: self.yourview.frame.size.height / self.yourview.frame.size.width,
constant: 0))
Swift 3:
yourView.addConstraint(NSLayoutConstraint(item: yourView,
attribute: .height,
relatedBy: .equal,
toItem: yourView,
attribute: .width,
multiplier: 9.0 / 16.0,
constant: 0))
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: