Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 206
Peter Stuart Avatar asked Oct 27 '13 23:10

Peter Stuart


People also ask

How do you make UILabel selectable?

The steps are as follows: Create a subclass of UILabel which you will use anywhere you want your label text to be selectable. Add a long press gesture recogniser. Upon long press, present the UIMenuController shared instance with the menu items you need, in this case, Copy and Speak.

How do I know if my UILabel is truncated Swift?

You can calculate the width of the string and see if the width is greater than label width. Save this answer.

What does sizeToFit do?

sizeToFit()Resizes and moves the receiver view so it just encloses its subviews.


3 Answers

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

like image 90
Manu Avatar answered Nov 17 '22 19:11

Manu


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

like image 2
Khanh Nguyen Avatar answered Nov 17 '22 19:11

Khanh Nguyen


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.

like image 2
iseletsky Avatar answered Nov 17 '22 17:11

iseletsky