我正在使用以下链接为本地货币符号和逗号自定义 UItextField:
http://www.thepensiveprogrammer.com/2010/03/customizing-uitextfield-formatting-for.html
NSNumber *actualNumber = [currencyFormatter numberFromString:[mstring
stringByReplacingOccurrencesOfString:localeSeparator withString:@""]];
在 iOS 5 中,这个实际数字始终为空,而在 iOS 4.x 中它工作正常
我的代码为此目的的主要方法是:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.tag == 1)
{
if(true)
{
NSMutableString* mstring = [[textField text] mutableCopy];
if([mstring length] == 0)
{
//special case...nothing in the field yet, so set a currency symbol first
[mstring appendString:[[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol]];
//now append the replacement string
[mstring appendString:string];
}
else
{
//adding a char or deleting?
if([string length] > 0)
{
[mstring insertString:string atIndex:range.location];
}
else
{
//delete case - the length of replacement string is zero for a delete
[mstring deleteCharactersInRange:range];
}
}
NSString* localeSeparator = [[NSLocale currentLocale]
objectForKey:NSLocaleGroupingSeparator];
NSNumber *actualNumber = [currencyFormatter numberFromString:[mstring
stringByReplacingOccurrencesOfString:localeSeparator
withString:@""]];
NSLog(@"%@",actualNumber);
[textField setText:[currencyFormatter stringFromNumber:actualNumber]];
[mstring release];
}
//always return no since we are manually changing the text field
return NO;
}
else
{
return YES;
}
}
这是初始化
NSLocale *paklocal = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_PAK"] autorelease];
currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setMaximumFractionDigits:0];
[currencyFormatter setLocale:paklocal];
NSMutableCharacterSet *numberSet = [[NSCharacterSet decimalDigitCharacterSet] mutableCopy];
[numberSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
nonNumberSet = [[numberSet invertedSet] retain];
[numberSet release];