我设置了一个UITextField来显示一个数字键盘。 如何要求用户准确输入 5 位数字?
我四处寻找,发现我应该使用shouldChangeCharactersInRange
但我不太明白如何实现它。
当用户离开文本字段/使用按钮进行验证时,我只会使用它
if ([myTextField.text length] != 5){
//Show alert or some other warning, like a red text
}else{
//Authorized text, proceed with whatever you are doing
}
现在,如果您想在用户键入时计算字符数,则可以在viewDidLoad
中使用
[myTextfield addTarget: self action@selector(textfieldDidChange:) forControlEvents:UIControlEventsEditingChanged]
-(void)textFieldDidChange:(UITextField*)theTextField{
//This happens every time the textfield changes
}
如果您需要更多帮助,请务必在评论中提问:)
使自己成为UITextFieldDelegate
的委托并实现以下内容:
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: @"n"].location != NSNotFound;
//desired length less than or equal to 5
return newLength <= 5 || returnKey;
}
- (BOOL) textField: (UITextField *)textField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
NSString *newText = [textField.text stringByReplacingCharactersInRange: range withString: string];
return [self validateText: newText]; // Return YES if newText is acceptable
}