需求:输入框内输入文字字数限制在20字。
方案一:采用了UITextField作为我的输入框控件,并且在委托方法:
1 | - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string |
中实现了对字符串的长度限制,实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #define kMaxLength 20 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (toBeString.length > kMaxLength && range.length!=1){ textField.text = [toBeString substringToIndex:kMaxLength]; return NO; } return YES; } |
方案二:注册这个观察者 UITextFieldTextDidChangeNotification
1 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextFieldTextDidChangeNotification object:nil]; |
然后实现这个通知方法即可。[……]