iOS7 UITextView contentsize.height 替代方案 [英] iOS7 UITextView contentsize.height alternative

查看:16
本文介绍了iOS7 UITextView contentsize.height 替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个应用程序从 iOS 6.1 移植到 iOS 7.我正在使用一个布局,其中有一个 UITextView 具有固定宽度,但它的高度基于其内容大小.对于 iOS 6.1,检查 contentsize.height 并将其设置为 textview 的框架高度就足够了,但它在 iOS 7 上不起作用.

I'm porting one of apps from iOS 6.1 to iOS 7. I'm using a layout where there's a UITextView that has a fix width, but it's height is based on its contentsize. For iOS 6.1 checking the contentsize.height and setting it as the textview's frame height was enough, but it doesn't work on iOS 7.

然后我如何创建一个 UITextView 具有固定宽度但基于它显示的文本的动态高度?

How can I then create a UITextView with a fixed width, but dynamic height based on the text it's showing?

注意:我是从代码中创建这些视图,而不是使用 Interface Builder.

NOTE: I'm creating these views from code, not with Interface Builder.

推荐答案

使用以下代码,您可以根据固定宽度更改 UITextView 的高度(适用于 iOS 7 和以前的版本):

With this following code, you can change the height of your UITextView depending of a fixed width (it's working on iOS 7 and previous version) :

- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
    UITextView *textView = [[UITextView alloc] init];
    [textView setAttributedText:text];
    CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}

使用此函数,您将使用 NSAttributedString 和固定宽度来返回所需的高度.

如果要从具有特定字体的文本计算框架,则需要使用以下代码:

If you want to calculate the frame from a text with a specific font you, need to use the following code :

- (CGSize)text:(NSString *)text sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
    {
        CGRect frame = [text boundingRectWithSize:size
                                          options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        return frame.size;
    }
    else
    {
        return [text sizeWithFont:font constrainedToSize:size];
    }
}

您可以将 SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO 添加到您项目中的 prefix.pch 文件中:

You can add that SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO on your prefix.pch file in your project as:

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

您还可以将之前的测试 SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) 替换为:

You can also replace the previous test SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) by :

if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])‌

这篇关于iOS7 UITextView contentsize.height 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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