Unable to reduce UILabel to match rotation content

I'm having trouble setting up my UILabel correctly using Auto Layout. Basically, I want my label to always be large enough to fit its content. Here are a few photos to demonstrate what I mean.

enter image description here

enter image description here

Pay attention to the additional top and bottom addition in landscape orientation. I do not want it. I want the label to be compressed vertically, so that it simply contains its contents.

I have an upper limit of 33 to the top layout guide, a leading limit of 75 for viewing and a limit on the end of 75 for viewing.

, - , - .

.

+3
3

, MaxLayoutWidth (, xib ..), , .

: IB iPhone :

iPhone Portrait

, :

- (void)updateLabelPreferredMaxLayoutWidthToCurrentWidth:(UILabel *)label
{
    label.preferredMaxLayoutWidth =[label bounds].size.width;
}

-(void)updateLabels
{
    [self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label1];
    [self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label2];
    [self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label3];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

    [self updateLabels];
}

MaxLayoutWidth willAnimateRotationToInterfaceOrientation, . :

iPhone Landscape

, updateLabels viewDidAppear :

-(void)viewDidAppear:(BOOL)animated
{
    [self updateLabels];
}

, xib iPhone, . , , .

iPad xib viewDidAppear:

iPad Portrait Demo

, .

+2

. , 0 100. UILabel 99. , , .

+1

: , : fooobar.com/questions/377191/...
, , , .


You can name sizeToFitthe label every time you change orientation. Theoretically, it is sizeToFitnot intended to be used with Auto Layout, but it should give you the effect you want. Here is the code you need in your view:

- (void)updateViewConstraints {
    [super updateViewConstraints];

    [self.label sizeToFit];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

    [self.view setNeedsUpdateConstraints];
}
+1
source

All Articles