要求 UITextField 取 5 位数
Require a UITextField to take 5 digits
我设置了一个 UITextField 来显示数字键盘。我如何要求用户准确输入 5 位数字?
我四处寻找,发现我应该使用 shouldChangeCharactersInRange
,但我不太了解如何实现它。
- (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
}
我只会在用户使用按钮
离开textfield/validates时使用它
if ([myTextField.text length] != 5){
//Show alert or some other warning, like a red text
}else{
//Authorized text, proceed with whatever you are doing
}
现在如果你想在用户输入时计算字符数,你可以使用 in 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;
}
我设置了一个 UITextField 来显示数字键盘。我如何要求用户准确输入 5 位数字?
我四处寻找,发现我应该使用 shouldChangeCharactersInRange
,但我不太了解如何实现它。
- (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
}
我只会在用户使用按钮
离开textfield/validates时使用它if ([myTextField.text length] != 5){
//Show alert or some other warning, like a red text
}else{
//Authorized text, proceed with whatever you are doing
}
现在如果你想在用户输入时计算字符数,你可以使用 in 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;
}