UITextView height according to content is wrong in iOS 9

痴心易碎 提交于 2019-12-10 17:32:24

问题


I adding views dynamically in to scrollview with layout constraint by programatically, For text view component I wanted to set the height constraint according to text set in textview, so I did created class extending UITextView. Inside text view class I have written following code to adding height constraint.

#import "CETextView.h"

@implementation CETextView

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (!self.heightConstraint)
    {
        self.heightConstraint =  [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100];
        [self addConstraint:self.heightConstraint];
    }
    CGRect lRect = [self contentSizeRect];

    CGSize descriptionSize = lRect.size;
    self.heightConstraint.constant = descriptionSize.height;

}

- (CGRect)contentSizeRect
{
    NSTextContainer* textContainer = [self textContainer];
    NSLayoutManager* layoutManager = [self layoutManager];
    [layoutManager ensureLayoutForTextContainer: textContainer];
    CGRect lRect = CGRectMake(0, 0,320, 500);
    lRect.size = self.contentSize;
    lRect.size.height = lRect.size.height + 5;
    return lRect;
}


@end

This code gives correct height in iOS 8.0 but gives wrong height in iOS 9.0. I Checked the apple doc for new release of iOS 9.0, there are some of the changes related auto layout.

Any help is appreciated.


回答1:


Not sure if you solved this or not, but I beat my head against the wall for a few hours until I made sure that enable scrolling was set to YES for the UITextViews I was trying to resize. Not sure if this will solve your issue, it seems slightly different.

iOS 8 resized the height just fine with enable scrolling set to NO, but it appears iOS 9 will not resize the height constraint if enable scrolling is NO. I just checked the box in the story board on all of my text views and everything resized after that.




回答2:


contentSize is not trustable since it updates until next runloop. You should use "sizeThatFits"



来源:https://stackoverflow.com/questions/32782716/uitextview-height-according-to-content-is-wrong-in-ios-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!