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

前端 未结 5 1589
Happy的楠姐
Happy的楠姐 2021-02-12 22:58

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 \'sizeWithF

5条回答
  •  北海茫月
    2021-02-12 23:14

    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!

提交回复
热议问题