How To Make Swift Buttons Auto Layout To Full Fill Screen Width Responsively In iOS

In previous article How To Add Constraints In Xcode 10 To Implement Auto Layout, we have learnt what is swift constraints, how to use it to pin a ui component on the screen and make auto layout, how to use constraints to align multiple ui components.

And we also show a demo use below example, you can find the example source code in article How To Prompt Alert Dialog When Click A Button In Swift. But the source code do not include the auto layout constraints code, this article will tell you how to add those auto layout constraints code.

Before Add Auto Layout Constraints Code.

change ios device orientation from portrait to landscape then fixed size ui component look ugly

After Add Auto Layout Constraints Code.

swift auto layout button when change screen orientation example

1. Add Auto Layout Constraints Code.

Below is the constraints that has been added to above three buttons. We will tell you how to add them use Xcode auto layout menu bar.

add height constraints and 4 direction space constraints to three buttons

Below is the Xcode auto layout menu bar. The five icon located at top right of View as iOS simulator list is just the auto layout menu buttons.

ios ui component constraints modifier menu bar with ios device simulator

1.1 Add Constraints For Button One.

Select Button One, click Add New Constraints icon in auto layout menu bar, then input below values in the popup dialog.
constraints value for button one

1.2 Add Constraints For Button Two.

Select Button Two, add constraints code to it like Button One, even the constraints constant value is same.

constraints value for button two

1.3 Add Constraints For Button Three.

This is similar with Button One and Button Two. Input below values in the popup Add New Constraints dialog.

constraints value for button three

Please note you should remove the Button Three’s bottom space constraints after adding it, because if not remove it, and when the iOS device size is changed( such as change iPhone to iPad ), Button Two‘s height value will be changed also.

You can see the result in below picture. This is because space constraints has higher priority than size ( height ) constraints, so when both direction space constraints and size constraints exist, space constraints will take effect first.

not remove button's bottom space constraints

0 0 votes
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x