I have a UITextField
that the user will enter an amount of money. I want to set it so it will show the users current currency. I could do the following:
<
If you are using ReactiveCocoa you can try doing this.
[textField.rac_textSignal subscribeNext:^(NSString *text) {
if (text.length < 4) text = @"0.00";
//set currency style
NSNumberFormatter *currencyFormatter = [NSNumberFormatter new];
currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
//leave only decimals (we want to get rid of any unwanted characters)
NSString *decimals = [[text componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
//insert decimal separator
NSMutableString *mutableString = [NSMutableString stringWithString:decimals];
[mutableString insertString:currencyFormatter.decimalSeparator atIndex:mutableString.length - currencyFormatter.minimumFractionDigits];
//I add currency symbol so that formatter recognizes decimal separator while formatting to NSNumber
NSString *result = [currencyFormatter.currencySymbol stringByAppendingString:mutableString];
NSNumber *formattedNumber = [currencyFormatter numberFromString:result];
NSString *formattedText = [currencyFormatter stringFromNumber:formattedNumber];
//saving cursors position
UITextRange *position = textField.selectedTextRange;
textField.text = formattedText;
//reassigning cursor position (Its not working properly due to commas etc.)
textField.selectedTextRange = position;
}];
It's not perfect, but maybe this can help you a bit in finding correct solution.