I have five UIView instances constrained using autolayout. When in portrait mode they fit into the screen, but when in landscape mode the screen becomes to small to contain all the views.
I know one way to solve this by creating two constraints and active one in portrait mode and deactivate the other and vice versa in landscape mode like this:
class ViewController : UIViewController{
var portraitHeight : NSLayoutConstraint!
var landscapeHeight : NSLayoutConstraint!
viewDidLoad(){
super.viewDidLoad()
portraitHeight = firstView.heightAnchor.constraint(equalToConstant: 88)
landscapeHeight = firstView.heightAnchor.constraint(equalToConstant: 68)
}
override func viewWillLayoutSubviews() {
let orientation = UIDevice.current.orientation
if orientation == .portrait
{
landscapeHeight.isActive = false
portraitHeight.isActive = true
}else if orientation == .landscapeLeft || orientation == .landscapeRight
{
portraitHeight.isActive = false
landscapeHeight.isActive = true
}
}
}
But what I really want is to be able to squish the views when there is not enough space. I tried changing UILayoutPriority but it didn't work.
These are my constraints:
NSLayoutConstraint.activate([
firstView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
firstView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor),
firstView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor),
firstView.heightAnchor.constraint(equalToConstant: 88),
secondView.topAnchor.constraint(equalTo: firstView.bottomAnchor),
secondView.leftAnchor.constraint(equalTo: firstView.leftAnchor),
secondView.rightAnchor.constraint(equalTo: firstView.rightAnchor),
secondView.heightAnchor.constraint(equalTo: firstView.heightAnchor),
thirdView.topAnchor.constraint(equalTo: secondView.bottomAnchor),
thirdView.leftAnchor.constraint(equalTo: firstView.leftAnchor),
thirdView.rightAnchor.constraint(equalTo: firstView.rightAnchor),
thirdView.heightAnchor.constraint(equalTo: firstView.heightAnchor),
fourthView.topAnchor.constraint(equalTo: thirdView.bottomAnchor),
fourthView.leftAnchor.constraint(equalTo: firstView.leftAnchor),
fourthView.rightAnchor.constraint(equalTo: firstView.rightAnchor),
fourthView.heightAnchor.constraint(equalTo: firstView.heightAnchor),
fifthView.topAnchor.constraint(equalTo: fourthView.bottomAnchor),
fifthView.leftAnchor.constraint(equalTo: firstView.leftAnchor),
fifthView.rightAnchor.constraint(equalTo: firstView.rightAnchor),
fifthView.heightAnchor.constraint(equalTo: firstView.heightAnchor),
])
Desired output:





