iOS 7 - UITextView大小字体,适合所有文本进入视图(无滚动) [英] iOS 7 - UITextView size font to fit all text into view (no scroll)

查看:395
本文介绍了iOS 7 - UITextView大小字体,适合所有文本进入视图(无滚动)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

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.

这适用于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;
}


推荐答案

解决方案1 ​​



您的问题可以通过简单地替换 sizeWithFont:constrainedToSize:来解决:

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



解决方案2



sizeThatFits 方法可以用来解决这个问题:

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!

这篇关于iOS 7 - UITextView大小字体,适合所有文本进入视图(无滚动)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆