TextField的字数限制的三种方法:
1.使用它的代理方法:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.titleField) {
if (string.length == 0) return YES;
NSInteger existedLength = textField.text.length;
NSInteger selectedLength = range.length;
NSInteger replaceLength = string.length;
if (existedLength - selectedLength + replaceLength > 20){
return NO;
}
}
return YES;
}
2.使用继承UIControl的方法,监听方法
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)textField
{
if (textField == self.titleField) {
if (textField.text.length > 20) {
textField.text = [textField.text substringToIndex:20];
}
}
}
3.使用通知方法
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:textField];
- (void)textFiledEditChanged:(NSNotification *)noti
{
UITextField *infoText = noti.object;
int kMaxLength = 20;
NSString *toBeString = infoText.text;
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
if ([lang isEqualToString:@"zh-Hans"]) { // 中文输入
UITextRange *selectedRange = [infoText markedTextRange];
//获取高亮部分
// 系统的UITextRange,有两个变量,一个是start,一个是end,这是对于的高亮区域
UITextPosition *position = [infoText positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if (toBeString.length > kMaxLength) {
infoText.text = [toBeString substringToIndex:kMaxLength];
}
}
// 有高亮选择的字符串,则暂不对文字进行统计和限制
else{
}
}
else{
if (toBeString.length > kMaxLength) {// 表情之类的,中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
infoText.text = [toBeString substringToIndex:kMaxLength];
}
}
}
对于高亮状态文字的解释:
比如你输入”abcd”,在textfield中显示的是”a b c d”,并且”a b c d”是处在高亮中的,并不算是真正输入到textfield中,所以我们不应把高亮的字符计算在内,我们应该计算真正输入的字符
网友评论