ios iOS7 UITextView contentsize.height 替代方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19028743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:43:59  来源:igfitidea点击:

iOS7 UITextView contentsize.height alternative

iosuitextviewios7

提问by Zoltan Varadi

I'm porting one of apps from iOS 6.1 to iOS 7. I'm using a layout where there's a UITextViewthat 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.

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

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

我如何才能UITextView根据它显示的文本创建一个具有固定宽度但动态高度的?

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

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

回答by Jordan Montel

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) :

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

- (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;
}

With this function, you will take a NSAttributedString and a fixed width to return the height needed.

使用此函数,您将使用 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];
    }
}

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

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

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

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

您还可以通过以下方式替换之前的测试SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)

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

回答by Ana

This worked for me for iOS6 and 7:

这对我来说适用于 iOS6 和 7:

CGSize textViewSize = [self.myTextView sizeThatFits:CGSizeMake(self.myTextView.frame.size.width, FLT_MAX)];
    self.myTextView.height = textViewSize.height;

回答by nova

In iOS7, UITextViewuses NSLayoutManagerto layout text:

在 iOS7 中,UITextView用于NSLayoutManager布局文本:

// If YES, then the layout manager may perform glyph generation and layout for a given portion of the text, without having glyphs or layout for preceding portions.  The default is NO.  Turning this setting on will significantly alter which portions of the text will have glyph generation or layout performed when a given generation-causing method is invoked.  It also gives significant performance benefits, especially for large documents.
@property(NS_NONATOMIC_IOSONLY) BOOL allowsNonContiguousLayout;

disable allowsNonContiguousLayoutto fix contentSize:

禁用allowsNonContiguousLayout修复contentSize

textView.layoutManager.allowsNonContiguousLayout = NO;

回答by Blake Hamilton

Use this little function

使用这个小功能

-(CGSize) getContentSize:(UITextView*) myTextView{
    return [myTextView sizeThatFits:CGSizeMake(myTextView.frame.size.width, FLT_MAX)];
}

回答by xZenon

My final solution is based on HotJard's but includes both top and bottom insets of text container instead of using 2*fabs(textView.contentInset.top) :

我的最终解决方案基于 HotJard 的,但包括文本容器的顶部和底部插入,而不是使用 2*fabs(textView.contentInset.top) :

- (CGFloat)textViewHeight:(UITextView *)textView
{
    return ceilf([textView.layoutManager usedRectForTextContainer:textView.textContainer].size.height +
                 textView.textContainerInset.top +
                 textView.textContainerInset.bottom);
}

回答by HotJard

There are simplier solution, using this method:

有更简单的解决方案,使用这种方法:

+(void)adjustTextViewHeightToContent:(UITextView *)textView;
{
    if([[UIDevice currentDevice].systemVersion floatValue] >= 7.0f){
        textView.height = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size.height+2*fabs(textView.contentInset.top);
    }else{
        textView.height = textView.contentSize.height;
    }
}

UPD: working just for displaying text (isEditable = NO)

UPD:仅用于显示文本(isEditable = NO)

回答by ChaoWang

   _textView.textContainerInset = UIEdgeInsetsZero;
   _textView.textContainer.lineFragmentPadding = 0;

Just don't forget the lineFragmentPadding

只是不要忘记 lineFragmentPadding

回答by Kirow

simple solution - textView.isScrollEnabled = falseworks perfect when inside another scroll view, or tableView cell with UITableViewAutomaticDimension

简单的解决方案 -textView.isScrollEnabled = false在另一个滚动视图或 tableView 单元格中完美运行UITableViewAutomaticDimension

回答by Baran Emre

@Ana's, @Blake Hamilton's solution in swift.

@Ana's, @Blake Hamilton's 解决方案swift

var contentHeight: CGFloat = textView.sizeThatFits(textView.frame.size).height

The good thing for me was that this also returns the correct contentSize, when isScrollEnableis set to false. Setting to false returned the text view's frame size instead of the content size.

对我来说好消息是这也返回了正确的contentSize, whenisScrollEnable设置为 false。设置为 false 返回文本视图的框架大小而不是内容大小。