[iOS]UITextView 输入字数限制
程序员文章站
2022-03-21 13:13:43
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { return textView.text.length + (text.length - range.length) <= 30;}...
1.超过长度的字符不允许输入
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
return textView.text.length + (text.length - range.length) <= 30;
}
2.输入后截取指定长度字符串
// 监听键盘
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChangeAction:) name:UITextViewTextDidChangeNotification object:nil];
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)textChangeAction:(NSNotification*)notf {
[self textViewMaxTextCount:self.inputTextView AndMaxCount:200];
}
// UITextView字数限制
- (void)textViewMaxTextCount:(UITextView *)textView AndMaxCount:(NSInteger)maxCount {
NSString *toBeString = textView.text;
NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage;
if ([lang isEqualToString:@"zh-Hans"]) { // 中文输入
UITextRange *selectedRange = [textView markedTextRange];
// 获取高亮部分
UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
if (!position) {// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (toBeString.length > maxCount) {
textView.text = [toBeString substringToIndex:maxCount];
[MBProgressHUD showError:[NSString stringWithFormat:@"字数不能超过%ld字",(long)maxCount]];
}
} else {//有高亮选择的字符串,则暂不对文字进行统计和限制
}
} else {//中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
if (toBeString.length > maxCount) {
textView.text = [toBeString substringToIndex:maxCount];
[MBProgressHUD showError:[NSString stringWithFormat:@"字数不能超过%ld字",(long)maxCount]];
}
}
_alertLab.text = [NSString stringWithFormat:@"%lu/%ld字",(unsigned long)textView.text.length,(long)_dataModel.limitNum];
}
本文地址:https://blog.csdn.net/u012881779/article/details/100584008
上一篇: 香蕉有点涩可以吃吗
下一篇: MotionLayout中与动画有关设置