views:

384

answers:

4

I have a UITextField in my IB and I want to check out if the user entered only numbers (no char)and get the integer value.

I get the integer value of the UITextField like that :

int integer = [myUITexrtField.text intValue];

When I put a character ( , ; . ) it return me 0 and I don't know how to detect that it is not only numbers.

How can I do?

+2  A: 

http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Objective-C

Or you could ensure that only the numeric keyboard appears when the focus comes on the field

Liam
A: 

You could also use UITextFieldDelegate method

textField:shouldChangeCharactersInRange:replacementString:

to live check that each time the user press a key, it is a simple digit, so that he/she knows that only int value is to be entered in the field.

dodecaplex
A: 

Change keyboard type to Numeric type..

iSwap
+1  A: 

Be sure to set your text field delegate

Use the following function to ensure user can type in numbers only:

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

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber* candidateNumber;

    NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    range = NSMakeRange(0, [candidateString length]);

    [numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];

    if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {

        return NO;
    }
    else 
    {
        return YES;
    }
}
Marichka