uitextfield check with only number

Asked

Viewed 542 times

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 and number for that textfield but I don’t know how to do it.

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 amount of characters just take the string from the field [[textField text] lenght]


Implementation in Swift:

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 of an application that I developed, Swift did not get to test 100%, but apparently this working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.