纯代码实现cell布局,利用约束实现自适应布局。
下面展示的为实现自适应输入框的部分关键代码
初始化cell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self updateViewConstraint];
}
return self;
}
设置布局的约束条件
- (void)setupViewConstraint {
[self.labelBeizhu mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.mas_equalTo(self.labelPriceTip.mas_leading);
make.top.mas_equalTo(self);
make.height.mas_equalTo(@(44));
make.width.mas_equalTo(@(50));
}];
[self.textViewBeiZhu mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.mas_equalTo(self.labelBeizhu.mas_trailing).offset(10);
make.top.mas_equalTo(self).offset(6);
make.height.mas_equalTo(@(32));
make.trailing.mas_equalTo(self).offset(-10);
make.bottom.mas_equalTo(self).priorityLow();
}];
}
textView的属性设置
- (UITextView *)textViewBeiZhu {
if (_textViewBeiZhu == nil) {
UITextView *textView = [[UITextView alloc] init];
textView.font = [UIFont systemFontOfSize:15];
textView.backgroundColor = [UIColor whiteColor];
textView.showsVerticalScrollIndicator = NO;
textView.scrollEnabled=NO;
textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
_textViewBeiZhu = textView;
[self addSubview:_textViewBeiZhu];
}
return _textViewBeiZhu;
}
在textViewDidChange中实时计算textview的高度并更新
- (void)textViewDidChange:(UITextView *)textView {
//计算textview高度
CGRect frame = textView.frame;
CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
CGSize size = [textView sizeThatFits:constraintSize];
[self.textViewBeiZhu mas_updateConstraints:^(MASConstraintMaker *make) {
//更新height
make.height.mas_equalTo(@(size.height));
}];
// 重点
[self.mtableView beginUpdates];
[self.mtableView endUpdates];
}