TextView
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// if ([text isEqualToString:@"\n"]) {
// [textView resignFirstResponder];
// return NO;
// }
NSString *totalText = [NSString stringWithFormat:@"%@%@",textView.text,text];
UITextRange *rangeSelected = textView.markedTextRange;
NSInteger validTxtLength = textView.text.length;
if (rangeSelected) { //在拼音的路上
NSString *selectedText = [textView textInRange:rangeSelected];
if (![self judgeInputIsChinese:text]) {//还是拼音
validTxtLength = totalText.length-selectedText.length;
if (validTxtLength > _maxLength) {
NSString *strValid = [textView.text substringWithRange:NSMakeRange(0, textView.text.length-selectedText.length)];
NSString *newStr = [strValid stringByAppendingString:text];
newStr = [newStr substringWithRange:NSMakeRange(0, _maxLength)];
textView.text = newStr;
return NO;
}else{
return YES;
}
}else{//拼完输入汉字了!=
NSString *strValid = [textView.text substringWithRange:NSMakeRange(0, textView.text.length-selectedText.length)];
NSString *newStr = [strValid stringByAppendingString:text];
if (newStr.length>_maxLength) {
newStr = [newStr substringWithRange:NSMakeRange(0, _maxLength)];
}
textView.text = newStr;
return NO;
}
}
if (totalText.length > _maxLength && text.length>0){//字段长度超过限制,且本步操作不是删除
textView.text = [totalText substringToIndex:_maxLength];
return NO;
}
if (![totalText isEqualToString:@""]) {
_txvPlaceholder.hidden = YES;
}
//删除最后一个字符时
if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
_txvPlaceholder.hidden = NO;
}
return YES;
}
//判断是否是全中文字符串
- (BOOL)judgeInputIsChinese:(NSString *)textStr{
NSString *regex = @"[\u4e00-\u9fa5]+";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [pred evaluateWithObject:textStr];
return isMatch;
}
参考文章:
网友评论