1
votes

I'm diving into autolayout and I'm trying to understand how to horizontally center multiple views, including views that have intrinsic sizes (like a UILabel or UIButton).

For example, I have a custom view with a fixed width of 320. In it, I have two subviews, a UILabel and an UIImageView. I want the UIImageView to be 15 pixels to the right of the UILabel and I want both the UILabel and the UIImageView together to be horizontally centered in the superview, but I'm not sure the best way to handle this.

Should I drop them in a container view and horizontally center the container view in the superview? If so, how do I determine the width of that container view if the UILabel has an intrinsic size?

Or, rather than putting them in a container view, should I calculate the width of the UILabel and use that value to sent the leading/trailing edges for the two views so that they are horizontally centered in the superview?

Thanks in advance for your wisdom!

1

1 Answers

4
votes

Using a container view is the simplest solution. If you create constraints between the container view and its label and image subviews, and you don't create any explicit width constraints on the container or the label, then the label will size itself to fit its content, and the container will size itself to fit its subviews. Then you can create a horizontal center constraint between the container and the top-level view.