I have 3 subviews(UILabel
, UIImageview
, UIButton
) to be laid out on a container view. All the subviews are laid out using visual format language (VFL). The subview have padding from the leading , top edges etc. The content of the subview are dynamic so their sizes changes all the time. i want to resize the superview(container view) to exactly fit all the subviews. Is this possible by auto layout? i have seen some of the link here which suggest intrinsic size which i am not able to understand. can someone suggest a better way to achieve this.
2 Answers
Yes, it's possible. If you plan to resize the superview according to subview content, then intrinsic content size is the way to go.
The ever excellent Ray Wenderlich site has a tutorial that covers this well. It's Beginning Auto Layout in iOS 6: Part 2/2:
Intrinsic Content Size
Before Auto Layout, you always had to tell buttons and other controls how big they should be, either by setting their frame or bounds properties or by resizing them in Interface Builder. But it turns out that most controls are perfectly capable of determining how much space they need, based on their content.
A label knows how wide and tall it is because it knows the length of the text that has been set on it, as well as the font size for that text. Likewise for a button, which might combine the text with a background image and some padding for the rounded corners.
The same is true for segmented controls, progress bars, and most other controls, although some may only have a predetermined height but an unknown width.
This is known as the intrinsic content size, and it is an important concept in Auto Layout. You have already seen it in action with the buttons. Auto Layout asks your controls how big they need to be and lays out the screen based on that information.
It is possible.
In my case, I wanted to give rounded corners to segmented control. For that, I embedded segmented control in UIView
. Now I was required to resize that container view as per size of segmented control.
I gave only following constraint and everything was taken care itself.
(1) Chose container view and give it X
and Y
constraints.
- Leading space to Super view.
- Top space to Super view.
(2) Chose container view and give Leading
| Trailing
| Top
| Bottom
constraint.
- Leading space to segmented control.
- Top space to segmented control.
- Trailing space to segmented control.
- Bottom space to segmented control.
(3) Chose segmented control and give it Height
and Width
constraints.
- Height : 30 // Whatever
- Width : 250 // Whatever
Now if I change the height and width of my segmented control, it automatically adjust container view's size (super-view of segmented control).