iOS 7 - UITextView大小字体,适合所有文本进入视图(无滚动)

Jim*_*med 17 resize uitextview sizewithfont ios7

我试图找到一个不推荐使用的方法来缩小textview的字体大小,以便所有文本都适合textview而不需要滚动.

不推荐使用'sizeWithFont'方法,我想确保最佳实践,XCode说要使用'boundingRectWithSize',但不知道如何使用它来缩小字体大小以使所有文本都适合.

有什么建议?不,我不能使用UILabel.我需要在顶部垂直对齐文本,UILabel不会这样做.

这适用于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;
}
Run Code Online (Sandbox Code Playgroud)

aks*_*h1t 21

解决方案1

只需更换以下内容即可解决您的问题sizeWithFont: constrainedToSize::

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

解决方案2

sizeThatFits方法可用于解决此问题,如下所示:

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];
}
Run Code Online (Sandbox Code Playgroud)

我希望其中一个解决方案可以解决您的问题.干杯!

  • 真棒!解决方案1对我不起作用,它实际上使字体非常大.但是解决方案2做到了!谢谢!! (2认同)