Frage

I have a UIVIew with a UILabel inside, an I want the UILabel and UIView to wrap the text content size. So I calculate the text size, and set the UIView's frame and the UIlabel's frame to the new height. The UIView get resized perfectly but the UILabel doesn't get resized. Stays always the same size. Don't know why

Here's my code:

[mylabel setNumberOfLines:0];
CGSize maximumLabelSize = CGSizeMake(mylabel.frame.size.width, 160);
CGSize expectedLabelSize = [text sizeWithFont:mylabel.font
                                      constrainedToSize:maximumLabelSize
                                          lineBreakMode:mylabel.lineBreakMode];
CGRect newFrame = mylabel.frame;
newFrame.size.height = expectedLabelSize.height;
mylabel.frame = newFrame;
mylabel.text = text;

myView.frame = CGRectMake(myView.frame.origin.x,
                                myView.frame.origin.y,
                                myView.frame.size.width,
                                newFrame.size.height);

PD: I'm changing the frames in viewDidLayoutSubviews, should I do it somewhere else?

UPDATE: I'm using Autolayout with some constraints. I need Autolayout because I have a nav bar and tab bar based app.

War es hilfreich?

Lösung

If you're using Autolayout, the layout constraints will dictate what the size of the views will be - It is not recommended that you use Autolayout and also change the frame of views because the results are not always predictable.

If you just want the UILabel to be the size of the UIView, then make sure UILabel has constraints for the height and width to be the same as the UIView. UILabels have an intrinsic size (the size that the label 'should' be). The label will always try to be it's intrinsic size unless constrained otherwise.

The view should have some constraint for what it's height/width are. if you set these in Xcode, set an IBOutlet into your controller for those constraints and alter the constant property.

If you want to animate a change in the constraints then you make your changes to the constraints you want changed and then call

[UIView animateWithDuration:.5f animations:^{
    [self.view layoutIfNeeded];
}];

calling layoutIfNeeded will cause the auto layout constraints to be reevaluated. calling it inside of an animation will animate the changed constraints.

From the look of things, what you want is the UILabel to be constrained to be the same height/width as the UIView, and to have an IBOutlet for a height constraint on the UIView. change the constant property on that IBOutlet to the desired height and then call layoutIfNeeded from inside an animation block.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top