When you add a UI component such as a button in the interface builder of Xcode project, you can adjust it’s position by hand. For example you place the button at center position both horizontally and vertically. But when you preview the screen in different devices or in different screen orientation. You will find the button is not layout properly. This article will tell you how to resolve this problem.
1. UI Layout Not Properly Problem.
In this example there is a button at the screen center. But when you change the screen orientation from portrait to landscape, you will find the button’s position is not behaved as expected like below. You can also choose different iOS devices in the bottom View as : area to see, the problem still exist.
This is because we do not add constraints to apply auto layout feature to the button to make it responsive to the orientation or device size change.
2. Add Auto Layout Constraints To UI Component.
There are five icons at the interface builder bottom right. Each icon has unique constraint manage functions.
- Align : Choose UI component layout align type between views, such as align to left, right, top, center and bottom.
- Add New Constraints : Add constraints value based on the align type.
- Resolve Auto Layout Issues: Resolve issues during constraints change, such as reset, clear or add missing constraints etc.
To add the auto layout constraints, just select the button and then click the Align icon and check Horizontally in Container and Vertically in Container checkbox. Then click Add 2 Constraints button to save them.
After that, there will add two constraints in the document outline view under View Controller —> View —> Constraints. Now in every device and orientation, the problem has been fixed. The button will change it’s position automatically with the screen change.
3. Custom The Button Auto Layout Constraints.
Now the button will be positioned at screen center in both orientation. But how to do if you want to place it at a special position. You can achieve this by change the constraints properties like below.
- Select one constraint under View Controller —> View —> Constraints.
- Then in the right panel, change both First Item and Second Item‘s value to Safe Area.Top in the drop down list. And input 100 in Constant value.
- Also change another constraint’s First Item and Second Item‘s value to Safe Area.Leading. And input 100 in Constant value.
- Now the button will be fixed at position(100, 100), and it will auto layout when the device or device screen orientation is changed.
- The Safe Area is the area that exclude the iOS device status bar. So the layout value is also relative to the safe area border.
- If you want to remove one auto layout constraints, just select the constraints and click the Resolve Auto Layout Issues icon in the constraints manager button bar at bottom, then select Clear Constraints menu item to remove it.