UITextView高度自适应和内部字数限制

2016-12-30  本文已影响0人  漂泊的飞鸟

第一步、在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);

}];

}

最后需要补充两点

1.通过textView.textContainerInset = UIEdgeInsetsMake(0 ,0, 30, 0);使限制文字出现在正在编写的那一行的下方,避免文字重叠。

2.如果涉及到复用或者隐藏之后再显示需要在显示的时候重新设置约束,即[self updateTextViewContains];再调用一次,不然会出现文字超出文本框的问题。

上一篇下一篇

猜你喜欢

热点阅读