How to constrain a UI component in a storyboard in XCode
Select the UI component and add constraints using the constraints or alignment menu.
Step One: Add a UI Component
Follow the tutorial below to learn how to add UI components to a storyboard.
Step Two: Set the Constraints
Select the UI component and open the relevant constraints menu:
- Constraints menu: For constraining the component to edges of a view or setting the width or height.
- Alignment menu: For horizontally and/or vertically aligning the component to the center of a view.
To set the constraints of a component to the edges of a view, select the relevant UI component and open the Constraints menu.
Click the relevant edges that you wish to constrain the UI component to. If they are selected, the constraints should appear in red.
You can change the offset (i.e. the distance from) by changing the number in the input next to the constraint.
Click the Add Constraints button to apply the constraints.
Please note that:
- For this to work, the UI component must fall under the view you wish to constraint it to. If it is not within the correct view, drag and drop it into the correct view.
- The edges that you are constraining to are the safe area insets of the view controller.
To learn how to constrain a UI component to the edges of the view of a UIViewController and not its safe area insets, follow the tutorial below.
To constrain the components width or height, select the relevant UI component and open the Constraint menu.
Check off the width and/or height and set the dimension by editing the value in the input next to the relevant constraint.
Click the Add Constraints button to apply the constraints.
To horizontally or vertically align a UI component to a view, select the component and open the Alignment menu.
Check off Horizontally in Container and/or Vertically in Container to horizontally or vertically align the UI component in the view.
Change the number in the input next to the relevant container to change the offset from the center.
Click the Add Constraints button to apply the constraints.
All constraints will appear on the Storyboard inspector, either under a views Constraints or within the UI components Constraints.