iOS7 UITextView contentsize.height alternative

2019-01-03 01:36发布

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.

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

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

9条回答
聊天终结者
2楼-- · 2019-01-03 01:36

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

查看更多
走好不送
3楼-- · 2019-01-03 01:38

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)

查看更多
看我几分像从前
4楼-- · 2019-01-03 01:40

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

- (CGFloat)textViewHeight:(UITextView *)textView
{
    return ceilf([textView.layoutManager usedRectForTextContainer:textView.textContainer].size.height +
                 textView.textContainerInset.top +
                 textView.textContainerInset.bottom);
}
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-03 01:41

This worked for me for iOS6 and 7:

CGSize textViewSize = [self.myTextView sizeThatFits:CGSizeMake(self.myTextView.frame.size.width, FLT_MAX)];
    self.myTextView.height = textViewSize.height;
查看更多
你好瞎i
6楼-- · 2019-01-03 01:41

Use this little function

-(CGSize) getContentSize:(UITextView*) myTextView{
    return [myTextView sizeThatFits:CGSizeMake(myTextView.frame.size.width, FLT_MAX)];
}
查看更多
冷血范
7楼-- · 2019-01-03 01:48

In iOS7, UITextView uses NSLayoutManager to layout text:

// 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 allowsNonContiguousLayout to fix contentSize :

textView.layoutManager.allowsNonContiguousLayout = NO;
查看更多
登录 后发表回答