1、#pragma mark- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (string.length ==0) returnYES;
// if (![selfvalidateNumber:string]) {
// returnNO;
// }
NSInteger existedLength = textField.text.length;
NSInteger selectedLength = range.length;
NSInteger replaceLength = string.length;
if (existedLength - selectedLength + replaceLength >11) {
returnNO;
}
}
returnYES;
}
2、
[textField addTarget:selfaction:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
这样就可以更好地限制输入长度:
- (void)textFieldDidChange:(UITextField *)textField
{
if (textField ==self.titleField) {
if (textField.text.length >11) {
textField.text = [textField.text substringToIndex:11];
}
}
}