上代码
UITextView
//每次TextView输入或删除的时候都会调用这个协议方法 <UITextViewDelegate>
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//用指定的字符串替换字符串,返回新的字符串
NSString * new = [textView.text stringByReplacingCharactersInRange:range withString:text ];
//保证新建通知的内容输入框最多只能输入4个字
NSInteger res = 4 - new.length;
if (res >= 0) {
return YES;
}else{
return NO;
}
}
但是这个方法如果输入是中文或者是联想词的时候都会出现问题,这是因为这个方法
NSString * new = [textView.text stringByReplacingCharactersInRange:range withString:text ];
不识别中文以及联想词。
在加一个这个就可以了
-(void)textViewDidChange:(UITextView *)textView
{
//如果是联想词的话下面 shouldChange。。。这个方法会无法识别
if (textView.text.length > 4) {
textView.text = [textView.text substringToIndex:4];
}
UITextField
#pragma mark - textField Delegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *new = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSInteger res = 4 - new.length;
if (res >= 0) {
return YES;
}else{
return NO;
}
}
//同样会有相同问题需要在加一个方法
[_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//shouldChangeCharacter不是识别中文和联想字所以在加一个这个,这个方法是自己写的,不是协议里已有的方法。
- (void)textFieldDidChange:(UITextField *)textField
{
if (textField == self.inputTxt) {
if (textField.text.length > 4) {
textField.text = [textField.text substringToIndex:4];
}
}
}
其实就是两个方法很简单。
来源:oschina
链接:https://my.oschina.net/u/2625446/blog/651996