Oys*_*sio 6 iphone cocoa-touch objective-c
我有UITextfield,用户可以输入一个美元金额,我希望textfield总是用两位小数格式化($.##).必须始终保持格式化.但我仍然坚持如何将输入的数字附加到文本字段中的现有数字?
//This delegate is called everytime a character is inserted in an UITextfield.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField tag] == amountTag)
{
NSString *amount = string;
//How do I append the already entered numbers in the textfield to the new entered values ?
//??
//Get new formatted value
NSString *newAmount = [self formatCurrencyValue:[amount doubleValue]];
[textField setText:[NSString stringWithFormat:@"%@",newAmount]];
return NO;
}
//Returning yes allows the entered chars to be processed
return YES;
}
-(NSString*) formatCurrencyValue:(double)value
{
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init]autorelease];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"$"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *c = [NSNumber numberWithFloat:value];
return [numberFormatter stringFromNumber:c];
}
Run Code Online (Sandbox Code Playgroud)
这是这个想法...
存储字符串值,附加到它,然后使用它进行操作。
在.h文件中定义一个NSMutableString
NSMutableString *storedValue;
@property (nonatomic, retain) NSMutableString *storedValue;
Run Code Online (Sandbox Code Playgroud)
合成它。
然后这样做...
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField tag] == amountTag)
{
[storedValue appendString:string];
NSString *newAmount = [self formatCurrencyValue:([storedValue doubleValue]/100)];
[textField setText:[NSString stringWithFormat:@"%@",newAmount]];
return NO;
}
//Returning yes allows the entered chars to be processed
return YES;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6312 次 |
| 最近记录: |