4

NSTextFieldユーザーのアクションに応じて編集可能に設定しています。ユーザーがウィンドウ内のテキスト フィールドの外側をクリックしたときに編集を終了したいと思います。

簡単に思えますが、これを機能させることができませんでした。と を実装controlTextDidEndEditingtextDidEndEditingましたが、特に最初の応答者のステータスを受け入れないユーザー インターフェイス要素をクリックするとうまくいきません。

4

4 に答える 4

2

すべての NSEvent は、NSWindow のsendEvent:メソッドを介して渡されます。

カスタム NSWindow を作成し、sendEvent:メソッドをオーバーライドできます。マウス ダウン イベントがある場合は、NSNotificationCenter によってブロードキャストします。

- (void)sendEvent:(NSEvent *)event {
    [super sendEvent:event];
    if (event.type == NSLeftMouseDown) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kCustomWindowMouseDown object:self userInfo:@{@"event": event}];
    }
}


NSTextField を参照する ViewController で、次の通知を観察します。

 [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(customWindowMouseDown:)
                                                 name:kCustomWindowMouseDown
                                               object:self.view.window];


マウス ダウン イベントの位置がテキスト フィールドの外にある場合は、編集を終了します。

- (void)customWindowMouseDown:(id)sender {
    NSNotification *notification = (NSNotification *) sender;

    NSEvent *event = notification.userInfo[@"event"];
    NSPoint locationInWindow = event.locationInWindow;

    if ([self.view.window.firstResponder isKindOfClass:NSTextView.class]) {
        NSTextView *firstResponder = (NSTextView *) self.view.window.firstResponder;

        //we only care about the text field referenced by current ViewController
        if (firstResponder.delegate == (id <NSTextViewDelegate>) self.textField) {

            NSRect rect = [self.textField convertRect:self.textField.bounds toView:nil];

            //end editing if click out side
            if (!NSPointInRect(locationInWindow, rect)) {
                [self.view.window makeFirstResponder:nil];
            }

        }
    }
}
于 2018-12-12T15:16:07.347 に答える
0

少し汚いかもしれませんが、「テキストフィールドの外側」領域に大きな透明なボタンを作成できます。編集開始時に表示し、編集終了時に非表示にします。ユーザーがこのボタンをタップすると、編集を停止します (そしてボタンを非表示にします)。

迅速な解決策が必要なときにそれを解決しました。

于 2012-10-23T05:17:07.180 に答える
0

NSView のサブクラスを記述し、以下のメソッドを記述して、nib ファイルの NSWindow で NSView のクラスをそのサブクラスに変更できます。

 - (void)mouseDown:(NSEvent *)event 
    {
         [text setEditable:NO];
         NSLog(@"mouseDown");
    }
于 2012-10-23T04:57:01.597 に答える