简体   繁体   中英

UITextView height according to content is wrong in iOS 9

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM