最近做项目有要求对输入昵称做字数限制,其中出现的问题记录一下:
刚开始是这么写的:
注册通知:
[NotificationCenter addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
- (void)textFieldTextDidChange:(NSNotification *)notification {
if (self.textfield.text.length) {
self.saveButtonItem.enabled = YES;
}else {
self.saveButtonItem.enabled = NO;
}
}
在代理方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *name = textField.text;
if (name.length > 20) {
return NO;
} else {
return YES;
}
}
这样写有2个问题:
1.需要正好输入限定的长度时才有用,一次性拼音拼出来的字超过固定长度时也会显示在textField上。
2.剩余1个字的时候拼音写完一个字符就不行了,因为拼写的拼音就是textField的内容,这样就导致比如你想输入我”,结果输入w的时候就已经到限制长度了。
所以最后这样写:
- (void)textFieldTextDidChange:(NSNotification *)noti {
if (self.textfield.text.length) {
self.saveButtonItem.enabled = YES;
}else {
self.saveButtonItem.enabled = NO;
}
NSString *language = [[[UITextInputMode activeInputModes] firstObject] primaryLanguage];
NSString *name = self.textfield.text;
if ([language isEqualToString:@"zh-Hans"]) {
UITextRange *range = [self.textfield markedTextRange];
UITextPosition *start = range.start;
UITextPosition *end = range.end;
NSInteger selLength = [self.textfield offsetFromPosition:start toPosition:end];
NSInteger contentLength = self.textfield.text.length - selLength;
if (contentLength > 20) {
self.textfield.text = [self.textfield.text substringToIndex:20];
}
}else {
if (name.length > 20) {
self.textfield.text = [self.textfield.text substringToIndex:20];
}
}
}
网友评论