Currency in UITextField

844 views Asked by At

I have a UITextField in which the user enters an amount of money. I am trying to make the textField show the current money symbol, as the user types in an amount.

So far I was able to do that in textFieldDIdEndEditing:, how can I do the following code in a method that lets you change as the user types. (For example shouldChangeTextInRange:.) This way the currency will always show, not only when the user is finished entering the amount.

Here is what I have so far:

- (void)textFieldDidEndEditing:(UITextField *)textField {

    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [currencyFormatter setLocale:[NSLocale currentLocale]];
    [currencyFormatter setMaximumFractionDigits:2];
    [currencyFormatter setMinimumFractionDigits:2];
    [currencyFormatter setAlwaysShowsDecimalSeparator:YES];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSNumber *someAmount = [NSNumber numberWithDouble:[textField.text doubleValue]];
    NSString *string = [currencyFormatter stringFromNumber:someAmount];

    textField.text = string;
}

The reason why I don't just insert it in a UILabel is because some places have their currency after the amount. (Ex. France)

2

There are 2 answers

1
Vikas Pandey On

Create a UIImageView with currency image.

And then set leftView either RightView of UITextField as per your requirement.

UIImage *cImage = [UIImage imageNamed:@"currency.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:cImage];
[imageView setFrame:CGRectMake(0, 0, 40, 40)];

// For Left
[textfield setLeftView:imageView];

// or

// For Right

[textfield setRightView:imageView];
3
Keyur Akbari On

Try this.

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == txtAmount) {
        if ([txtAmount.text isEqualToString:@""]) {
            txtAmount.text = @"$";
        }else{
            txtAmount.text = [NSString stringWithFormat:@"%@",txtAmount.text];
        }
    }

    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == txtAmount) {
        if ([txtAmount.text isEqualToString:@"$"]) {
            txtAmount.placeholder = @"Amount";
        }
    }
    return YES;
}

and don't forget to give delegate to the UITextField.