iOS autolayout to center my view between two views
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction to iOS Auto Layout
Auto Layout is a powerful constraint-based layout system available in iOS that allows developers to create adaptable and flexible user interfaces. It helps ensure that your app's user interface (UI) looks good on different devices, orientations, and sizes without needing to manually adjust layout components.
Centering a View Between Two Views
One common layout requirement is to center a view between two other views. In this context, we will demonstrate how to use Auto Layout in Interface Builder and programmatically in Swift to accomplish this task.
Using Interface Builder
Auto Layout constraints can be easily created in Interface Builder using Xcode. To center a view (let's call it middleView
) between leftView
and rightView
, follow these steps:
- Add Views to the View Controller: First, ensure that all three views (
leftView,middleView,rightView) are added to your ViewController's view. - Pin Edges: Add constraints to pin
leftViewto the left edge of the superview andrightViewto the right edge:leftView.leading = superView.leadingrightView.trailing = superView.trailing
- Set Widths: Establish the widths for
leftViewandrightView:leftView.width = rightView.width
- **Center
middleView**: Create constraints to centermiddleView:middleView.centerX = (leftView.trailing + rightView.leading)/2- Align the vertical center of
middleViewif necessary.
- Vertical Constraints: Ensure that all views have constraints for vertical positioning (e.g., top/bottom alignment or fixed height).
Programmatically in Swift
Below is an example of how to create the same constraints programmatically:
- Dynamic Widths: Instead of fixed widths, consider relative widths using multipliers to adapt dynamically to different screen sizes.
- Priority Adjustments: Use varying constraint priorities to manage competing constraints effectively.

