It doesn\'t sound too difficult, but after hours of trying I couldn\'t get a proper solution.
Problem: I want to set constraints (with class NSLayoutAnchor) to get a
The key to making this work is to set the width of the colorImageView
equal to the width of its superview but with a priority of 750 (instead of the default 1000).
Then set the height of the colorImageView
to be lessThanOrEqualTo
the height of its superview.
Auto Layout will do its best to satisfy these two new constraints.
When the view's width is greater than its height, it won't be able to make the colorImageView
s width equal to the view's width, but that's OK since the priority is 750. It will make it as big as possible without violating the other full priority constraints.
When the view's height is greater than its width, it will be able to satisfy all constraints because the colorView's height is lessThanOrEqualTo
the view's height.
import UIKit
let view = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 100))
view.backgroundColor = .red
let colorImageView = UIView()
colorImageView.translatesAutoresizingMaskIntoConstraints = false
colorImageView.backgroundColor = .yellow
view.addSubview(colorImageView)
// CREATE CONSTRAINTS(center in SuperView)
colorImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
colorImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// CREATE CONSTRAINTS (ratio 1:1)
colorImageView.widthAnchor.constraint(equalTo: colorImageView.heightAnchor, multiplier: 1.0).isActive = true
let widthConstraint = colorImageView.widthAnchor.constraint(equalTo: view.widthAnchor)
widthConstraint.priority = UILayoutPriority(rawValue: 750)
widthConstraint.isActive = true
colorImageView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor).isActive = true
view.layoutIfNeeded()
view.frame = CGRect(x: 0, y: 0, width: 60, height: 50)
view.layoutIfNeeded()
Here it is running in a Playground: