I am making a "preferences" screen, and struggling with the layout aspect of the top header. I have a simple "back" button, and a label. The requirement is, the back button must always be floated left, and the label must be at the center, with its own content centered.
So far, I created a stackview (horizontal) containing both the items. I have specified distribution to equal spacing, and added width constraints as follows: button - 60 label - 200
This looks good on one screen, but I am sure it is not gonna work because screen widths vary on different devices and also between portrait/landscape.
In CSS, this would have simply been specifying that the button be float:left and the label be margin:auto, how do I make this work in the XIB?
Here is a screenshot for reference:
You have a few options...
The simplest, and closest to your CSS description:
Button is constrained 0 from top, 8 from leading (adjust as desired); label is constrained centered vertically to button, centered horizontally to view.
The drawback: if label gets too much text, it will overlap the button.
Second option:
Same as above, but add a "spacer" UIView
to upper right... constrain it 0 to top, 8 to trailing, centered vertically to button, and constrain it equal width and equal height to button. Then, add >= 8
constraints to the label leading to button trailing, and label trailing to spacer view leading. That will allow the label to expand horizontally based on its text, but will prevent overlap (text will be ...
truncated if there is too much to fit).
Third option - using stack view:
Stack view settings:
Axis: Horizontal
Alignment: Fill
Distribution: Fill
Spacing: 8
Constrain the stack view 0 to top, 8 leading and trailing (just for a little padding on the sides), add a button, label and UIView
. Constrain the
"spacer" view equal width to the button. Set the Horizontal Content Hugging Priority = 1000
for the button (will keep it the width of its title).
There are other approaches, partially depending on if you want to do anything else you haven't shown here, but all three of these will do the job.