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

In the previous article How To Add Constraints In Xcode 10 To Implement Auto Layout, we have learned what is swift constraints, how to use swift constraints to pin a UI component on the screen and make it 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 the article How To Prompt Alert Dialog When Click A Button In Swift. But the source code does not include the auto layout constraints code, this article will tell you how to add those auto layout constraints code.

1. Add Auto Layout Constraints Code.

  1. Below are the constraints that have been added to the three buttons. We will tell you how to add them use the Xcode auto-layout menu bar.
  2. Below is the Xcode auto-layout menu bar. The five icons located at the top right corner of the View as iOS simulator list are just the auto layout menu buttons.

1.1 Add Constraints For Button One.

  1. Select Button One, click Add New Constraints icon in the auto layout menu bar, then input the below values in the popup dialog.

1.2 Add Constraints For Button Two.

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

1.3 Add Constraints For Button Three.

  1. This is similar to Button One and Button Two. Input below values in the popup Add New Constraints dialog.
  2. Please note you should remove Button Three’s bottom space constraints after adding it because if not remove it, and when the iOS device screen size is changed( such as change iPhone to iPad ), Button Two‘s height value will be changed also.
  3. You can see the result in the below picture. This is because space constraints have higher priority than size ( height ) constraints, so when both direction space constraints and size constraints exist, space constraints will take effect first.

Leave a Comment

Your email address will not be published. Required fields are marked *

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