Set auto-detection limits to device size

I fell into the trap of relying on Autolayout. I currently have a ViewController with tons of UIViews and realized that they are distorted on smaller devices (iPhone 4 and 5).

Is it possible to set limits in Autolayout regarding the size of the device.

For example, I have one UIView with several other aligned UIViews . I would like to change the height in Autolayout of this UIView to be half the height of the device.

+6
source share
1 answer

Yes. There is a way to limit the screen size.

They are called size classes .

In the Builder interface, look at the panel at the bottom of the screen where wAny hAny , these are drop-down lists. Select the combination of height and width of the device and the orientation you want to limit, and when you create restrictions in this mode, they will correspond to this size / orientation. You can also add and change size limits in the editor panel of the inspector limiter in Interface Builder.

If you need to fine-tune some things with an angular case that you cannot manage to do quite conveniently with the help of size clans, you can make an IBOutlet for restriction and refer to it in your code and change it when the view appears and changes, similar to the following example. This is much simpler and safer than trying to create software restrictions from scratch.

Note. When changing the NSLayout constraint through IB output, you can only configure the constant field, not the multiplier , because multiplier read-only at runtime. Therefore, any scaling factor that you use (if any) should be multiplied by any final value that you use for the constant.

 @IBOutlet var tableYTopConstraint : NSLayoutConstraint! override func viewWillAppear(animated: Bool) { adjustViewLayout(UIScreen.mainScreen().bounds.size) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { adjustViewLayout(size) } func adjustViewLayout(size: CGSize) { switch(size.width, size.height) { case (320, 480): // iPhone 4S in portrait tableYTopConstraint.constant = 0 case (480, 320): // iPhone 4S in landscape tableYTopConstraint.constant = 0 case (320, 568): // iPhone 5/5S in portrait tableYTopConstraint.constant = 0 case (568, 320): // iPhone 5/5S in landscape tableYTopConstraint.constant = 0 case (375, 667): // iPhone 6 in portrait tableYTopConstraint.constant = 0 case (667, 375): // iPhone 6 in landscape tableYTopConstraint.constant = 0 case (414, 736): // iPhone 6 Plus in portrait tableYTopConstraint.constant = 0 case (736, 414): // iphone 6 Plus in landscape tableYTopConstraint.constant = 0 default: break } view.setNeedsLayout() } 
+9
source

Source: https://habr.com/ru/post/984074/


All Articles