Search code examples
ios7resizeuitextviewsizewithfont

iOS 7 - UITextView size font to fit all text into view (no scroll)


I am trying to find a non-deprecated method to size the font of a textview down so that all text fits in the textview without requiring scrolling.

The method 'sizeWithFont' is deprecated and I want to ensure best practices, and XCode says to use 'boundingRectWithSize' but not sure how to use this to size a font down so that all text fits.

Any suggestions? And NO I can not use a UILabel instead. I need to have the text vertically aligned at the top and UILabel does not do this.

This worked Pre-iOS 7:

CGFloat fontSize;
CGFloat minSize;
if([deviceType isEqualToString:@"iPad"] || [deviceType isEqualToString:@"iPad Simulator"]){
    fontSize = 40;
    minSize = 15;
}
else{
    fontSize = 18;
    minSize = 8;
}
while (fontSize > minSize)
{
    CGSize size = [quote sizeWithFont:[UIFont fontWithName:@"Interstate" size:fontSize] constrainedToSize:CGSizeMake(newView.frame.size.width, 10000)];

    if (size.height <= newView.frame.size.height) break;

    fontSize -= 1.0;
}

Solution

  • Solution 1

    Your problem can be solved by simply replacing sizeWithFont: constrainedToSize: with :

    boundingRectWithSize:CGSizeMake(newView.frame.size.width, FLT_MAX)
                    options:NSStringDrawingUsesLineFragmentOrigin
                 attributes:@{NSFontAttributeName:[UIFont fontWithName:@"Interstate" size:fontSize]}
                    context:nil];
    

    Solution 2

    The sizeThatFits method can be used to address this problem like this:

    while (fontSize > minSize &&  [newView sizeThatFits:(CGSizeMake(newView.frame.size.width, FLT_MAX))].height >= newView.frame.size.height ) {
        fontSize -= 1.0;
        newView.font = [tv.font fontWithSize:fontSize];
    }
    

    I hope one of these solutions solve your problem. Cheers!