Constraints

How to change constraints so the objects on the screen scale correctly for every device?

Accepted Reply

You can add your constraints programmatically or by using Storyboards, depending on the requirements for your app. For example, to programmatically pin an item to its superView by it's safeAreaLayoutGuide, you could type :

leadingAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.leadingAnchor, constant: constant).isActive = true

trailingAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.trailingAnchor, constant: -constant).isActive = true

topAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.topAnchor, constant: constant).isActive = true

bottomAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.bottomAnchor, constant: -constant).isActive = true


In a Storyboard you would check the box for "Use Safe Area Layout Guides" by opening the Utilities -> File Inspector -> Interface Builder Document :



Hopefully this helps :-)

Replies

you can set constraints respective to the view safe area. Top, left, center...


that hat covers many use cases


you could also use all the variations in IB, but that rapidly becomes complex when there are many constraints.


you can also define IBOutlets for those constraints and change their constant programmaticall.

So should i set all the contraints to safe area

that’s what I do to avoid issues with iPhoneX

Yes, for devices running iOS 11+ you should use the safeAreaLayoutGuide :

<https://developer.apple.com/documentation/uikit/uiview/2891102-safearealayoutguide>


Here is a guide you can utilize for reference :

https://developer.apple.com/documentation/uikit/uiview/positioning_content_relative_to_the_safe_area

Will that make the items on screen shrink or become larger depending on the screen size?

It depends on the constraints you set.


But effectively, if you set a leading and a trailing margin for a field, it will adapt automatically to screen width.

How should I go about doing that?

You can add your constraints programmatically or by using Storyboards, depending on the requirements for your app. For example, to programmatically pin an item to its superView by it's safeAreaLayoutGuide, you could type :

leadingAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.leadingAnchor, constant: constant).isActive = true

trailingAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.trailingAnchor, constant: -constant).isActive = true

topAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.topAnchor, constant: constant).isActive = true

bottomAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.bottomAnchor, constant: -constant).isActive = true


In a Storyboard you would check the box for "Use Safe Area Layout Guides" by opening the Utilities -> File Inspector -> Interface Builder Document :



Hopefully this helps :-)

Thanks