关于C#:要求UITextField取5位数字

Require a UITextField to take 5 digits

本问题已经有最佳答案,请猛点这里访问。

我有一个UITextField设置为显示数字键盘。 我如何要求用户输入准确的5位数字?

我戳了一下,发现我应该使用shouldChangeCharactersInRange,但是我不太了解如何实现它。


当用户使用按钮离开文本字段/验证时,我将只使用它

1
2
3
4
5
6
7
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中使用

1
2
3
4
5
[myTextfield addTarget: self action@selector(textfieldDidChange:) forControlEvents:UIControlEventsEditingChanged]

-(void)textFieldDidChange:(UITextField*)theTextField{
 //This happens every time the textfield changes
}

如果您需要更多帮助,请确保在评论中提出问题:)


使自己成为UITextFieldDelegate的代表,并实现以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (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: @"
"
].location != NSNotFound;

        //desired length less than or equal to 5
        return newLength <= 5 || returnKey;
    }


1
2
3
4
5
6
7
- (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

}