UITextField实现字数限制
当要对UITextField进行字数限制的时候,可以使用- (BOOL)textField: shouldChangeCharactersInRange: replacementString: 这个方法实现需要以下的几个步骤:1、在在@interface中声明代理,@interface ZWCardViewController () <UITextFieldDelegate>
2、在设置UITextField的delegate,在viewDidLoad方法中实现,
self.IDCardTextField.delegate = self; (或者在storyboard上来设置这个delegate)
3、实现代理的方法,
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *IDCardText = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField == self.IDCardTextField) { // 指定哪一个textField来做限制
if (IDCardText.length > 18) {
textField.text = [IDCardText substringToIndex:18];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
return YES;
}