Using a UITextField like an ATM keypad.

A small snippet of code that uses a UITextField like an ATM keypad. E.g. You start typing in a sequence like this:

£0.00 -> £0.02 -> £0.20 -> £2.05 -> £20.50

Elsewhere define and store a reference to a NSNumberFormatter like so:

        self.en_GB = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
        self.paymentFormatter = [[NSNumberFormatter alloc] init];
        [self.paymentFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        [self.paymentFormatter setLocale:self.en_GB];
        [self.paymentFormatter setGeneratesDecimalNumbers:YES];        

Then as a delegate method to the UITextField:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
    
    NSMutableString *mutableString = [[textField text] mutableCopy];
    
    if ([mutableString length] == 0) {
        [mutableString setString:[self.en_GB objectForKey:NSLocaleCurrencySymbol]];
        [mutableString appendString:string];
    } else {
        if ([string length] > 0) {
            [mutableString insertString:string atIndex:range.location];
        } else {
            [mutableString deleteCharactersInRange:range];
        }
    }
    
    NSString *penceString = [[[mutableString stringByReplacingOccurrencesOfString:
                               [self.en_GB objectForKey:NSLocaleDecimalSeparator] withString:@""]
                              stringByReplacingOccurrencesOfString:
                               [self.en_GB objectForKey:NSLocaleCurrencySymbol] withString:@""]
                              stringByReplacingOccurrencesOfString:
                               [self.en_GB objectForKey:NSLocaleGroupingSeparator] withString:@""];
    
    self.paymentPence = [NSDecimalNumber decimalNumberWithString:penceString];
    
    [textField setText:[self.paymentFormatter stringFromNumber:[self.paymentPence decimalNumberByMultiplyingByPowerOf10:-2]]];
    
    return NO;
}

I want to keep the amount in pence, hence the self.paymentPence property. On the off-chance that the UK moves to the € I also use a NSLocale instance to make sure Decimal Separators, Currency Separators and Symbols are correct rather than hard coded.

This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

2 Responses to Using a UITextField like an ATM keypad.

Comments are closed.