xonegirlz
xonegirlz

Reputation: 8967

multiple line autoresizing text UILabel

Is it possible to have a multiline UILabel that auto-resizes the UIFont size so that it fits into the frame size of a UILabel? If not then what is the best way to achieve this? I don't want to adjust the frame size of the UILabel/UITextView to whatever. So far I've been doing it like this:

int currentFontSize = 18;
    UIFont *currentFont = [UIFont fontWithName:kProximaNovaBold size:currentFontSize];
    CGSize storyTitleSize = [storyTitle sizeWithFont:currentFont constrainedToSize:self.newsfeedStoryTitle_.frameSize];

    while (storyTitleSize.height >= self.newsfeedStoryTitle_.frameHeight){
        currentFontSize--;
        currentFont = [UIFont fontWithName:kProximaNovaBold size:currentFontSize];
        storyTitleSize = [storyTitle sizeWithFont:currentFont constrainedToSize:self.newsfeedStoryTitle_.frameSize];
    }

    [self.newsfeedStoryTitle_ setFont:currentFont];
    [self.newsfeedStoryTitle_ setText:storyTitle];

Upvotes: 1

Views: 1056

Answers (1)

coneybeare
coneybeare

Reputation: 33101

You want: sizeWithFont:constrainedToSize:lineBreakMode: [Source]

//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(self.bounds.size.width, NSIntegerMax);

CGSize expectedLabelSize = [theString sizeWithFont:the Font constrainedToSize:maximumLabelSize lineBreakMode:theLineBreakMode];   

//adjust the label the the new height.
CGRect newFrame = theLabel.frame;
newFrame.size.height = expectedLabelSize.height;
theLabel.frame = newFrame;

Upvotes: 3

Related Questions