I want to create UILabel and some other elements with code. UILabel size can change depending on the text, so I must move other elements accordingly. How can I do that most effectively? I try to access bounds property, but strangely, it is null:
CGRect textRect = CGRectMake(20, 20, 280, 50);
label = [[UILabel alloc] initWithFrame:textRect];
label.text = someString;
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
[superView addSubview: label];
NSLog(@"bounds: %@", label.bounds);
prints out “bounds: (null)”
The label itself renders just fine in the expected coordinates.
The bounds property is a CGRect. A CGRect is not an Objective-C object, so you can’t print it directly using
%@. You need to convert it to a string first usingNSStringFromCGRect:The best way to handle laying out the
UILabeland the elements around it is by creating a customUIViewsubclass to contain the label and other elements, and overriding itslayoutSubviewsmethod to do the layout.For example, let’s say we want to have the label and an image view, and we want the image view to be flush against the bottom edge of the label. We can create a
UIViewsubclass namedContainerView:We can use this as the superview of the label and an image view. We’ll rely on the ContainerView to lay out the label and the image, so we don’t need to specify their frames. We’ll also rely on the ContainerView to add the label and the image view as subviews.
Here’s how we implement ContainerView (assuming we’re using ARC):
We’ll override ContainerView’s ‘label’ setter to add the label as a subview:
We do the same for the ‘imageView’ setter:
The interesting part is the
layoutSubviewsmethod. The system sends thelayoutSubviewsmessage to a view at various times, including after it gets new subviews and when its size changes.