-4

当用户以下面提到的所需格式输入文本时,我需要格式化文本。

1)当用户输入0作为第一个字符时,文本字段应显示文本为0.00

2)当用户输入1作为第二个字符时,文本字段应显示为0.01

3)当用户输入2作为第三个字符时,文本字段应显示为0.12

4)当用户输入3作为第四个字符时,文本字段应显示为1.23

5)当用户输入4作为第五个字符时,文本字段应显示为12.34

这应该一直持续到7 个整数位。最高值应为99,99,999.00

我曾尝试使用数字格式化程序,但无法做到这一点。如果有任何解决方案会非常有帮助吗?

除此之外,我还需要在文本和逗号分隔符之前添加一个 $ 符号。

4

1 回答 1

1

由于您希望 UITextField 最多具有 7 个整数位,因此您需要验证每个修改,并防止任何导致大于 7 个整数位的数字。我知道的最简单的方法是 UITextFieldDelegate 方法shouldChangeCharactersInRange

- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {

    NSString* modifiedFieldText = [textField.text stringByReplacingCharactersInRange:range withString:string] ;
    // Remove all characters except for the digits 0 - 9.
    NSString* filteredToDigits = [modifiedFieldText stringByFilteringCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]] ;
    // Change textField's text only if the result is <= 9 digits  (7 integer digits and 2 fraction digits).
    if ( filteredToDigits.length <= 9 ) {
        // If you'd rather this method didn't change textField's text and only determined whether or not the change should proceed, you can move this code block into a method triggered by textField's Editing Changed, replacing this block with "return YES".  You'll need to once again filter textField's text to only the characters 0 - 9.
        NSNumberFormatter* numberFormatter = [NSNumberFormatter new] ;
        numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle ;

        NSNumber* asNumber = @( filteredToDigits.doubleValue / 100.0 ) ;
        textField.text = [numberFormatter stringFromNumber:asNumber] ;
    }
    // This method just changed textField's text based on the user's input, so iOS should not also change textField's text.
    return NO ;
}

我使用 NSString 类别将 @"$12,345.67" 更改为 @"1234567"。

NSString+过滤器.m

- (NSString*) stringByRemovingCharactersInSet:(NSCharacterSet*)charactersToRemove {
    return [[self componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""] ;
}
- (NSString*) stringByFilteringCharactersInSet:(NSCharacterSet*)charactersToKeep {
    NSCharacterSet* charactersToRemove = [charactersToKeep invertedSet] ;
    return [self stringByRemovingCharactersInSet:charactersToRemove] ;
}
于 2013-03-12T20:08:37.897 回答