Require a UITextField to take 5 digits [duplicate]

社会主义新天地 提交于 2020-01-05 10:17:25

问题


I have a UITextField set up to show a number pad. How do I require the user to enter exactly 5 digits?

I poked around and saw I should use shouldChangeCharactersInRange but I'm not quite understanding how to implement that.


回答1:


I'd just use this when the user leaves the textfield/validates with a button

if ([myTextField.text length] != 5){

//Show alert or some other warning, like a red text

}else{
 //Authorized text, proceed with whatever you are doing
}

Now if you want to count the chars WHILE the user is typing, you might use in viewDidLoad

[myTextfield addTarget: self action@selector(textfieldDidChange:) forControlEvents:UIControlEventsEditingChanged]

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

Please make sure to ask questions in the comments if you need more help :)




回答2:


Make yourself a delegate of UITextFieldDelegate and implement the following:

- (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;
    }



回答3:


- (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 

}


来源:https://stackoverflow.com/questions/27840460/require-a-uitextfield-to-take-5-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!