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

查看:75
本文介绍了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天全站免登陆