Create individual constraints for different iPhone sizes (not interested in the iPad)

Hello everybody,


I am developing my first iOS app and I am super excited. I am only developing for iPhone in portrait.


I would like to use different constraint sizes for the different iPhone screen sizes but I can't do it. Size classes does not work becuase the the width is always compact and the height is always regular.


How can I set different constrait sizes on the different sizes?


Thanks,

Depends what you want to achieve.


Those constraints for inbstance will yield same result on all :


- center vertically or horizontally in superview

- leading or trailing to superview

- top or bottom to superview


In fact, you ought to set constraints relative to safe area.

For exeample, on the iPhone SE on portrait I want the constraint to the top to be 20 and on the iPhone X I want that same constrait on portrait to be 40.


How do I achieve that?

>I am only developing for iPhone in portrait.


Actually, you're not. Review expects your app, even if iPhone-only, to not look bad when run in 1x/2x mode on iPad, and unless you can show a hard requirement for not providing landscape support, you can expect push back during review.


>How can I set different constrait sizes on the different sizes?


See:

- https://developer.apple.com/design/adaptivity/Auto Layout

- https://developer.apple.com/design/tips/

Why do you want 20 and then 40 ?


If it is because of the notch, the safe area is just done for this.

This was just an example. In some displays I want the elements to be "more together". In larger displays I would like to see the elements further from each other.


Does it work if I change the relation to greater than or equal?

If you want to adapt to screen size, you can adjust the constraints in code.


- create an IBOutlet for the constraint :

@IBOutlet var topConstraint: NSLayoutConstraint!

- change its value where you need (may be in viewDidLoad

if screenSize.height > someValue {
     topConstraint.constant = 40
} else {
     topConstraint.constant = 20
}

If I do that, can I set the constraints on the storyboard?

Yes, you first define constraints in the storyboard, for instance at 20.

You create the IBOutlet for the constraint: control-drag from the constraint (in the pane that lists all objects) to the code


Then you modify them in code, as proposed.

Create individual constraints for different iPhone sizes (not interested in the iPad)
 
 
Q