限制输入的字数
1.遵守UITextFieldDelegate
@interface TestViewController ()<UITextFieldDelegate>
2.设置代理
self.testTextField.delegate = self;
3.实现代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField == self.testTextField) { if (range.location >= 11) {//限制只允许输入11位 return NO; } } return YES; }
计算剩余字数
前两步一样,代理方法如下
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField == self.testTextField) { if (range.location >= 11) { return NO; } }else { NSInteger remainNum = 11 - textField.text.length; } return YES; }
remainNum即是剩余字数