要求 UITextField 采用 5 位数字



我设置了一个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 
}

最新更新