2

インターフェイスビルダーには、テキストフィールドにドラッグできるこのカスタムフォーマッターがあります。

ここに画像の説明を入力

しかし、これにはプロパティがまったくなく、Apple によくあるように、ドキュメントは存在しません。

数字、英数字セットのテキスト、およびアンダースコアを受け入れ、他のすべてを拒否できるフォーマッターを作成する必要があります。

このカスタム フォーマッタが必要だと思いますが、どのように使用すればよいですか? または、インターフェースビルダーに存在する通常のフォーマッターを使用して必要なことを行うことは可能ですか?

インターフェイスビルダーを使用した例を挙げていただけますか?

ありがとう。

4

2 に答える 2

2

NSFormatter クラスは抽象クラスなので、サブクラス化する必要があります。その上で、次のメソッドを実装する必要があります。

- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error;
- (NSString *)stringForObjectValue:(id)obj;
- (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string errorDescription:(out NSString **)error;

次のようなサブクラスを作成します。

.h

@interface MyFormatter : NSFormatter

@end

.m

@implementation MyFormatter

- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error
{
    // In this method you need to write the validation
    // Here I'm checking whether the first character entered in the textfield is 'a' if yes, It's invalid in my case.
    if ([partialString isEqualToString:@"a"])
    {
        NSLog(@"not valid");
        return false;
    }
    return YES;
}

- (NSString *)stringForObjectValue:(id)obj
{
    // Here you return the initial value for the object
    return @"Midhun";
}

- (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string errorDescription:(out NSString **)error
{
    // In this method we can parse the string and pass it's value (Currently all built in formatters won't support so they just return NO, so we are doing the same here. If you are interested to do any parsing on the string you can do that here and pass YES after a successful parsing
    // You can read More on that here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFormatter_Class/index.html#//apple_ref/occ/instm/NSFormatter/getObjectValue:forString:errorDescription:
    return NO;
}
@end
于 2015-03-15T10:11:51.380 に答える
1

このオブジェクトは、OS X で最も役立ちます。OS X では、フォーマッタをコントロール/セルにアタッチできます。iOS では、NIB やストーリーボードにフォーマッタを追加してアウトレットを接続できると思いますが、プログラムで作成するよりも大きな利点はありません。

特に、汎用カスタム フォーマッタは、 のカスタム サブクラスのインスタンスを追加する場合に使用しますNSFormatter。カスタム フォーマッタを関連するコントロール/セルにドラッグし、アイデンティティ インスペクタでそのクラスを設定します。

そのオブジェクトがオブジェクト ライブラリで利用できない場合は、特定のフォーマッタ クラス (例: NSNumberFormatter) のインスタンスのみをドラッグできます。結果のインスタンスのクラスを設定できますが、その特定のフォーマッタ クラスのサブクラスにしか設定できません。

カスタム フォーマッタ クラスの作成方法を学習する必要がある場合は、 のクラス リファレンスNSFormatterData Formatting Guideを参照してください。

于 2015-03-15T10:10:23.130 に答える