Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make text field that to accept only 4 digit or numbers in iphone

I have an app in which I want to enter a numeric value in UITextField. But I want to allow only 4 digits to be entered. So 1234 would be valid but 12345 cannot be entered. Any idea how how I can modify this to accept only a numeric value limited to 4 digits?

like image 999
Queen Solutions Avatar asked Aug 31 '13 09:08

Queen Solutions


2 Answers

Sample Code :

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *currentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    int length = [currentString length];
    if (length > 4) {
       return NO;
    }
    return YES;
}
like image 67
Bhavin Avatar answered Oct 05 '22 22:10

Bhavin


Swift 3.0 Xcode 8.3.3...

First UITextField set the delegate and then put this code...

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let textstring = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let length = textstring.characters.count
    if length > 4 {
        return false
    }
    return true
}

Objective C Code...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
      {
        NSString *textstring = [textField.text stringByReplacingCharactersInRange:range withString:string];
        int length = [textstring length];
        if (length > 4) {
           return NO;
        }
            return YES;
      }
like image 21
Arjun Yadav Avatar answered Oct 05 '22 22:10

Arjun Yadav