In general, auto layout is performed in a top-down fashion. In other words, a parent view layout is performed first, and then any child view layouts are performed. So asking the system to size the parent based on the child is a bit like swimming upstream, harder to do, but still possible with some work.
One solution is to use the intrinsic size of a view.
For example, a UILabel
has an intrinsic size based on the text in the label. If a UILabel
has a leading constraint and a top constraint, but no other constraints, then its width and height are determined by its intrinsic size.
You can do the same thing with a custom view class that encloses a UILabel. By setting the intrinsic size of the custom view class based on the intrinsic size of the UILabel, you get a view that automatically resizes based on the text in the label.
Here's what the code looks like for the custom class. The .h
file defines a single property text
. The .m
file has an IBOutlet to the child label. Setting and getting the text
property simply sets or gets the text from the label. But there's one very important twist, setting the text invalidates the intrinsic size of the parent. That's what makes the system adjust the size of the parent view. In the sample code below the parent is sized to have an 8 pixel margin all around the UILabel.
SurroundView.h
@interface SurroundView : UIView
@property (strong, nonatomic) NSString *text;
@end
SurroundView.m
@interface SurroundView()
@property (weak, nonatomic) IBOutlet UILabel *childLabel;
@end
@implementation SurroundView
- (void)setText:(NSString *)text
{
self.childLabel.text = text;
[self invalidateIntrinsicContentSize];
}
- (NSString *)text
{
return( self.childLabel.text );
}
- (CGSize)intrinsicContentSize
{
CGSize size = self.childLabel.intrinsicContentSize;
size.height += 16;
size.width += 16;
return( size );
}
@end
Creating the IBOutlet to the childLabel
can be a little tricky, so here's the procedure
- drag out a UIView into the storyboard
- use the Identity inspector to change the class to
SurroundView
- drag out a UILabel and add it as a subview of the
SurroundView
- select the label, and open the assistant editor
- show
SurroundView.m
in the assistant
- drag from the open circle to the label as shown below

All that's left is to get the constraints right. The constraints for the label should look like this

The constraints for the SurroundView
should be as shown below. The key point is that the Intrinsic Size should be set to Placeholder to avoid the warnings about missing constraints.
