限制文本编辑字数的方法整理

最近在项目中发现原来的一些代码的textFiled在限制字数上总是出现这样或那样的问题,今天就来整理一下几种常用的方法.

第一种比较简单粗暴,索然也能达到想要的结果,但是用户体验不太好:

-(void)textFieldDidEndEditing:(UITextField *)textField{

if (textField.text.length > 5) {

textField.text = [textField.text substringToIndex:5];

}

}

//点击return结束编辑

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

[textField resignFirstResponder];

return YES;

}

就是在textFiled的代理方法中结束编辑时判断一下字数长度进行截断,比较生硬.

第二种方法是动态的判断文本框中字数,以达到判断的目的,也是使用textFiled的代理方法

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

NSString *tostring = [textField.text stringByReplacingCharactersInRange:range withString:string];

//必须加上markedTextRange的判断,否则在系统自带的输入法中会把未选中之前的拼音也算成字符串长度,若在搜狗输入法上不加此判断也没有问题

if (textField.markedTextRange == nil) {

if (tostring.length > 5) {

textField.text = [tostring substringToIndex:5];

return NO;

}

}

return YES;

}

第三种方法使用textFiled中提供的监听方式UITextFieldTextDidChangeNotification:

首先在viewwillappear中设置监听

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextFiledDidChangeAction:) name:UITextFieldTextDidChangeNotification object:nil];

然后实现监听到事件时要执行的方法

-(void)TextFiledDidChangeAction:(NSNotification *)noti{

//必须加上markedTextRange的判断,否则在系统自带的输入法中会把未选中之前的拼音也算成字符串长度,若在搜狗输入法上不加此判断也没有问题

if (_textFiled.markedTextRange == nil) {

if (_textFiled.text.length>5) {

_textFiled.text = [_textFiled.text substringToIndex:5];

}

NSLog(@"change");

}

}

但是第二种方式的话只有在不符合条件后再次触发键盘才会返回NO,因此第三种方式作为合适

你可能感兴趣的:(限制文本编辑字数的方法整理)