UITextField check with only number

0

I am creating a tableview with Cells custon via xib and UITableViewCell and I have a cell that has only one textField and I want to do a check of number of characters and numbers for this textfield but I do not know how to do that.

    
asked by anonymous 20.08.2015 / 17:18

1 answer

1

You can use the UITextField delegate

Implementation in Objective-C:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Within this method you can check the type of value you are receiving:

NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

if(!(([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:@""])) {
    return NO;
}

To limit the number of characters, just take the string from the field [[textField text] lenght]

Swift deployment:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let nonNumberSet:NSCharacterSet = NSCharacterSet.decimalDigitCharacterSet();

    if count(string.stringByTrimmingCharactersInSet(nonNumberSet)) > 0 {
        return false;
    }

    return true;

}

The implementation in Objective-c is an application that I developed, Swift did not test 100%, but apparently is working.

    
20.08.2015 / 18:14