Development‎ > ‎Macintosh関連‎ > ‎

HowTo - NSTextFieldに入力制限を行う


概要

NSTextFieldにはフォーマッターの定義もできますが、文字の入力制限は実装されていないため、どのような文字でも入力できてしまいます。
ここでは、任意のNSTextFieldに数値入力制限(数値以外は入力できない)の実装方法を示します。


対象


Xcode4, Objecttive-C, Mac OS X 10.7以上
iOS4以上の場合でも、UIオブジェクトに関係する部分を置き換えることで流用できます。


方法

下記の方法に従ってください。
  1. NSTextFieldの入力(つまり、変更)を受け取るには、NSNotificationCenterの「NSControlTextDidChangeNotification」通知を受け取れるようにする必要があります。
    Code

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(controlTextDidChange:) name:NSControlTextDidChangeNotification object:nil];

    上記「object:nil」に任意のオブジェクトを渡すと、そのオブジェクトに関する通知のみがなされます。
    ここでは、デリゲート先で同じタイプのオブジェクトを一括で処理できるようにしていますので「nil」を渡しています。

  2. 上記で定義した通知先を実装します。
    これは、
    上記「addObserver」で指定したオブジェクト内に設置する必要があります。
    Code
    -(void)controlTextDidChange:(NSNotification *)notification
    {
    // 下記でNSTextField以外は処理を行わないようにしています。
    if( [[[notification.object class] description] isEqualToString:@"NSTextField"] )
    {
    // NSTextFieldオブジェクトを通知データ「notification」から取り出し、
    // 該当する「identifier」かチェックしています。
    // 下記では「
    numerical_limits_identifier」と定義されていることが前提となります。
    NSTextField *text = (NSTextField*)notification.object;
    if( [[text identifier] isEqualToString:@"numerical_limits_identifier"] )
    {
    // 正規表現を使い、数値以外を含んでいないかチェックします。
    NSString *work = [text stringValue];
    NSError *error = nil;
    NSRegularExpression *regexp =
    [NSRegularExpression
    regularExpressionWithPattern:@"^[0-9]" 
    options:0
    error:&error];
    if( !error )
    {
    NSTextCheckingResult *match =
    [regexp firstMatchInString:work options:0 range:NSMakeRange(0, work.length)];
    // match.numberOfRangesが1以外の場合には数値以外が含まれていることになる。
    if( match.numberOfRanges != 1 )
    {
    // 下記で文字列以外の文字を空白で置換しています。
    regexp = [NSRegularExpression
    regularExpressionWithPattern:@"[^0-9]"
    options:0
    error:&error
    ];
    NSString *str = [regexp 
    stringByReplacingMatchesInString:work
    options:NSMatchingReportProgress 
    range:NSMakeRange(0, work.length) 
    withTemplate:@""];
    [text setStringValue:str];
    }
    }
    }
    }
    }
これで、NSTextFieldに数値制限を設けることができました。
対象となるNSTextFieldオブジェクトの「identifier」に上記のように同じものを定義しておくと、ここに処理しなくて済みます。

SelectionFile type iconFile nameDescriptionSizeRevisionTimeUser