简体   繁体   中英

How do I add constraints so that my view's dimensions do not change when the orientation changes?

I want my view to have the following properties (the numbers are arbitrarily chosen):

  • width is equal to height divided by 1.2
  • stays at the bottom right of the screen
  • height is 1/7 of the screen's height when in portrait
  • width and height does not change when the orientation changes

The first three requirements can be easily translated into UILayoutConstraint s. I have done them with SnapKit just because it reads more clearly. You should see what I mean even if you have never used SnapKit before.

let myView = UIView(frame: .zero)
myView.backgroundColor = .green
view.addSubview(myView)
myView.snp.makeConstraints { (make) in
    make.right.equalToSuperview().offset(-8)
    make.bottom.equalToSuperview().offset(-8)
    make.width.equalTo(myView.snp.height).dividedBy(1.2)
    make.height.equalTo(view.snp.height).dividedBy(7) // *
}

The problem is the last bullet point. When I rotate the device from portrait to landscape, what was originally the width before the rotation, becomes the height after the rotation. This causes my view to become smaller as a result.

Basically, I want to replace the constraint marked with * with something like this:

make.height.equalTo(max(view.snp.height, view.snp.width)).dividedBy(7)

but I don't think max(a, b) is a thing in SnapKit or the UILayoutConstraint API.

Surely there is some other way of expressing "equal to whichever length is longer", right?

PS I didn't tag this with because I would also accept an answer that uses the UILayoutConstraint API.

Looks like you have 2 options:

  1. Hardcode the height value.
  2. Try to use nativeBounds :

This rectangle is based on the device in a portrait-up orientation. This value does not change as the device rotates.

In this case the height is always be for portrait mode.

myView.snp.makeConstraints { make in
    make.right.bottom.equalToSuperview().offset(-8)
    let screenHeight = UIScreen.main.nativeBounds.height / UIScreen.main.nativeScale
    let height = screenHeight / 7
    make.width.equalTo(height).dividedBy(1.2)
    make.height.equalTo(height)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM