is a microblog
home archives search feed blogroll


sizeToFit is broken for labels on iOS. If the text is too long, the label will be larger than the screen even if you set numberOfLines to 0.

I wrote a category to fix it.

#import "UILabel+O9.h"

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width

@implementation UILabel (O9)

- (void)o9_sizeToReallyFit {
    [self sizeToFit];

    int screenWidthTimes = (int) (self.frame.size.width / SCREEN_WIDTH);

    if (screenWidthTimes > 0) {
        self.frame = CGRectMake(self.frame.origin.x,
                                self.frame.size.height * (screenWidthTimes + 1));


The function calls a regular sizeToFit and then adjusts the width and height of the frame based on how many times larger than the screen the label is.

This could be improved to support landscape mode as well.

Why did I even have to write this? Sometimes iOS sucks. Even sizeThatFits: and adjustsFontSizeToFitWidth didn’t work.

Reminder: Casting a float to an int floors the value (does not ceil).

Posted on 2018-03-23   #ios     #objc  

← Next post    ·    Previous post →