接到一个需求:评论输入框控制用户只能输入200个字。于是在
- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
//添加如下代码
NSString* toBeString = [textView.textstringByReplacingCharactersInRange:rangewithString:text];
if(toBeString.length>self.maxTextInputNum) {
returnNO;
}
}
可是这样的话,可以在输入中文的时候无限点击提示,于是各种搜索,找到了以下方法:
适用于textView textField
+ (void)limitTextInputWithNotification: (NSNotification *)noti InMaxLength: (CGFloat)length {
id textInput;
if ([noti.object isKindOfClass:[UITextField class]]) {
textInput = (UITextField *)noti.object;
} else if ([noti.object isKindOfClass:[UITextView class]]) {
textInput = (UITextView *)noti.object;
} else {
return;
}
NSString *toBeString = [textInput text];
// if ([noti.object isKindOfClass:[UITextField class]]) { //昵称禁止输入表情
// [textInput setText:[self disable_emoji:[textInput text]]];
// }
NSString *lang = [[textInput textInputMode] primaryLanguage];
if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
{
//获取高亮部分
UITextRange *selectedRange = [textInput markedTextRange];
UITextPosition *position = [textInput positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position)
{
if (toBeString.length > length)
{
[textInput setText:[toBeString substringToIndex:length]];
}
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else
{
if (toBeString.length > length)
{
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:length];
if (rangeIndex.length == 1)
{
[textInput setText:[toBeString substringToIndex:length]];
}
else
{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, length)];
[textInput setText: [toBeString substringWithRange:rangeRange]];
}
}
}
}
使用时候发送通知即可:
_NC_Add(self, @selector(textViewEditChanged:),UITextViewTextDidChangeNotification, nil);
监听通知:
- (void)textViewEditChanged:(NSNotification *)notif;
{
[Untitles limitTextInputWithNotification:notif InMaxLength:200];
}