UITextView高度自适应和内部字数限制
第一步、在setupUI方法里创建空间
//文本框
UITextView*textView = [[UITextViewalloc]init];
textView.delegate=self;
[self.contentViewaddSubview:textView];
self.textView= textView;
textView.textContainerInset=UIEdgeInsetsMake(0,0,30,0);
textView.layer.borderColor= [UIColorgrayColor].CGColor;
textView.layer.borderWidth=1.0;
// textView.layer.cornerRadius = 5.0;
//文本框内部字数限制label
NSString*str = [NSStringstringWithFormat:@"(%zd/50)",_length];
ZGTXLabel*limitLabel = [ZGTXLabellabelWithFont:10text:str];
[self.contentViewaddSubview:limitLabel];
[self.contentViewbringSubviewToFront:limitLabel];
self.limitLabel= limitLabel;
第二步、在(void)layoutSubviews方法中布局,这里我用的Masonry
-(void)layoutSubviews
{
[superlayoutSubviews];
//文本框
[self.textViewmas_makeConstraints:^(MASConstraintMaker*make) {
make.left.equalTo(self.clickRecordBtn.mas_right).offset(8);
make.top.equalTo(self.clickRecordBtn.mas_top);
make.right.offset(-8);
// make.bottom.offset(0);
make.height.offset(50);
}];
//限制字数label
[self.limitLabelmas_makeConstraints:^(MASConstraintMaker*make) {
make.right.equalTo(self.textView.mas_right).offset(-3);
make.bottom.equalTo(self.textView.mas_bottom).offset(-3);
}];
}
第三步、设置UITextView代理
#pragma UITextViewDelegate
- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
if([textisEqualToString:@""] && range.length>0) {
//删除字符肯定是安全的
returnYES;
}
else{
if(textView.text.length- range.length+ text.length>50) {
UIAlertView*alert = [[UIAlertViewalloc]initWithTitle:@"超出最大可输入长度"message:nildelegate:selfcancelButtonTitle:@"确定"otherButtonTitles:nil];
[alertshow];
returnNO;
}
else{
returnYES;
}
}
}
-(void)textViewDidChange:(UITextView*)textView{
[self updateTextViewContains];
}
//修改文本框约束
-(void)updateTextViewContains
{
CGRect frame = self.textView.frame;
CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
CGSize size = [self.textView sizeThatFits:constraintSize];
if (size.height >= maxHeight)
{
size.height = maxHeight;
self.textView.scrollEnabled = YES; // 允许滚动
}
else
{
self.textView.scrollEnabled = NO; // 不允许滚动
}
self.length = (NSInteger *)self.textView.text.length;
[self.textView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.clickRecordBtn.mas_right).offset(8);
make.top.equalTo(self.clickRecordBtn.mas_top);
make.right.offset(-8);
make.height.offset(size.height);
}];
}