UITextView使用相對較少,研究了下發(fā)現(xiàn)代理方法并不多,算是簡單控件了。這里針對字?jǐn)?shù)限制功能的開發(fā)稍作總結(jié):
//創(chuàng)建UITextView,注意添加代理
UITextView *textView = [[UITextView alloc]init];
textView.text = @"占位文字";
textView.delegate = self; //UITextViewDelegate
textView.textColor = hexStringToColor(@"C2C2C2");
textView.font = [UIFont systemFontOfSize:14];
[cell.contentView addSubview:textView];
[textView makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_offset(15*layoutBy6());
make.top.mas_offset(10*layoutBy6());
make.right.mas_offset(-15*layoutBy6());
make.bottom.mas_offset(-10*layoutBy6());
}];
#pragma mark - TextViewDelegate
//輸入時(shí)自動刪除占位文字
- (void)textViewDidBeginEditing:(UITextView *)textView{
if ([textView.text isEqualToString:@"占位文字"]) {
textView.text = @"";
}
}
//當(dāng)編輯時(shí)動態(tài)判斷是否超過規(guī)定字?jǐn)?shù),這里限制20字
- (void)textViewDidChange:(UITextField *)textView{
if (textView.text.length > 20) {
textView.text = [textView.text substringToIndex:20];
}
//這里的_strLengthLbl為動態(tài)顯示已輸入字?jǐn)?shù),可按情況添加
_strLengthLbl.text = [NSString stringWithFormat:@"%lu/20",textView.text.length];
}
//編輯結(jié)束后如內(nèi)存為空自動添加占位文字
- (void)textViewDidEndEditing:(UITextView *)textView{
if ([textView.text isEqualToString:@""]) {
textView.text = @"占位文字";
}
}