Peter Stuart
Peter Stuart

Reputation: 2444

How can I prevent sizeToFit from changing the UILabel width?

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

The problem I am having is that if each time the UILabel.text value changes, the UILabel width changes according to the content of the label.

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

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

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

Thanks,

Peter

Upvotes: 6

Views: 8072

Answers (4)

Parimal
Parimal

Reputation: 277

Use following trick to do the job done:

First is set tag of uiLabel. My cell.yourLable tag 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 the trick is to get same UiLabel by tag and set its width by setting frame.

Upvotes: 0

iseletsky
iseletsky

Reputation: 653

I subclassed UILabel and overrode the sizeThatFits method to look like this:

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

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

Then if I add the label into a nib I place a UILabel from the object library. After that I make sure to set the class of the placed label to my custom class instead of the default of UILabel.

It basically just overrides the new width with the original width so it never changes width, but dynamically changes height.

Upvotes: 2

Khanh Nguyen
Khanh Nguyen

Reputation: 11132

Use [UILabel sizeThatFits:] with a CGSize with infinite height like (320, 10000).

Upvotes: 2

Manu
Manu

Reputation: 788

you can create a category or a subclass of UILabel and add this method to resize only the height of the label depending to the input text

- (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];
}

and use it instead sizeToFit

Upvotes: 7

Related Questions