简体   繁体   English

如何使 Tab 键将焦点移出 NSTextView?

[英]How can I make the Tab key move focus out of a NSTextView?

I'm using an NSTextView to allow multi-line input.我正在使用 NSTextView 来允许多行输入。 However, due to the nature of my app, users will be more comfortable moving to the next input element when they press TAB.但是,由于我的应用程序的性质,用户在按下 TAB 时会更舒服地移动到下一个输入元素。

How can I make TAB exit the NSTextView, while keeping the newline behaviour of the Enter key?如何让 TAB 退出 NSTextView,同时保持 Enter 键的换行行为?

You could implement -textView:doCommandBySelector: in your text view's delegate:您可以在文本视图的委托中实现-textView:doCommandBySelector:

- (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector {
    if (aSelector == @selector(insertTab:)) {
        [[aTextView window] selectNextKeyView:nil];
        return YES;
    }

    return NO;
}

See http://developer.apple.com/documentation/Cocoa/Reference/NSTextViewDelegate_Protocol请参阅http://developer.apple.com/documentation/Cocoa/Reference/NSTextViewDelegate_Protocol

You'll need to implement this in a subclass.您需要在子类中实现它。

I wrote such a subclass for Translate Text .我为Translate Text写了这样一个子类。 You're welcome to use it under its BSD license .欢迎您在其 BSD 许可下使用它。 Here's the header and the implementation file .这是头文件实现文件

… while keeping the newline behaviour of the Enter key? …同时保持 Enter 键的换行行为?

My main purpose was to send an action to a target when the user presses Enter, and I also have it drop focus from the view.我的主要目的是在用户按下 Enter 时向目标发送一个动作,并且我还让它从视图中删除焦点。 However, both are explicit statements in the code;但是,两者都是代码中的显式语句; you can simply comment that code out or delete it.您可以简单地注释掉该代码或删除它。

Swift version of the answers of Wevah & Quinn: Wevah & Quinn 答案的 Swift 版本:

func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    switch commandSelector {
    case #selector(NSResponder.insertTab(_:)):
        textView.window?.selectNextKeyView(nil)
        return true
    case #selector(NSResponder.insertBacktab(_:)):
        textView.window?.selectPreviousKeyView(nil)
        return true
    default:
        return false
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM