How can I prevent UILabel from resizing width to sizeToFit?

I have UILabel right now and the value of UILabel.text changes regularly.

The problem is that if each time the value of UILabel.text changes, the width of the UILabel changes according to the contents of the label.

How can i fix this? This is my code that I have right now:

outputLabel.text = errorMessage;
outputLabel.hidden = NO;
[outputLabel sizeToFit];

UPDATE The reason I use sizeToFit is because I need the height to automatically change.

Thanks,

Peter

+4
source share
4 answers

UILabel

- (void)heightToFit {

    CGSize maxSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
    CGSize textSize = [self.text sizeWithFont:self.font constrainedToSize:maxSize lineBreakMode:self.lineBreakMode];

    CGRect labelRect = self.frame;
    labelRect.size.height = textSize.height;
    [self setFrame:labelRect];
}

sizeToFit

+7

[UILabel sizeThatFits:] CGSize , (320, 10000).

+2

UILabel sizeThatFits, :

- (CGSize)sizeThatFits:(CGSize)size
{
    CGSize res = [super sizeThatFits:size];

    return CGSizeMake(size.width, res.height);
}

, nib, UILabel . , UILabel.

, , .

+1

, :

The uiLabel tag is set first. Cell.yourLable is 998

cell.yourLable.numberOfLines = 0;
[cell.yourLable sizeToFit];

UILabel *myLbl=[cell.contentView viewWithTag:998];
CGRect frm=cell.yourLable.frame;
frm.size.width = cell.contentView.frame.size.width;
myLbl.frame=frm;

Here's the trick is to get the same UiLabel by tag and set its width by setting the frame.

0
source

All Articles