I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it
After many many hours of problems with textviews in table view cells, this was the solution that worked for me. I'm using Masonry, but the constraints could be created in IB as well.
Note that the textview delegate is not used. This is advantageous because it doesn't matter whether you change the text programmatically or via user input. Either way layoutSubviews gets called whenever a text view changes its contents.
If you want to have this directly in your view controller you could use viewDidLayoutSubviews instead of layoutSubviews.
@implementation TextViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self){
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectZero];
textView.scrollEnabled = NO;
self.textView = textView;
[self.contentView addSubview:self.textView];
[self.textView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(self.contentView.mas_leadingMargin);
make.trailing.equalTo(self.contentView.mas_trailingMargin);
make.top.equalTo(self.contentView.mas_topMargin);
make.bottom.equalTo(self.contentView.mas_bottomMargin);
make.height.lessThanOrEqualTo(@100.0).with.priorityHigh();
make.height.greaterThanOrEqualTo(@30.0).with.priorityHigh();
}];
}
return self;
}
- (void)layoutSubviews{
CGSize size = [self.textView sizeThatFits:CGSizeMake(self.textView.bounds.size.width, 10000)];
self.textView.scrollEnabled = size.height > 100.0;
[super layoutSubviews];
}
@end