-4

ユーザーが下記の目的の形式でテキストを入力するときに、テキストをフォーマットする必要があります。

1) ユーザーが最初の文字として0を入力すると、テキスト フィールドにはテキストが0.00として表示されます。

2) ユーザーが 2 番目の文字として1を入力すると、テキスト フィールドは0.01として表示されます。

3) ユーザーが 3 番目の文字として2を入力すると、テキスト フィールドは0.12として表示されます。

4) ユーザーが 4 番目の文字として3を入力すると、テキスト フィールドは1.23と表示されます。

5) ユーザーが 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+Filter.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 に答える