NSTextView中的按键事件(macOS)

时间:2016-08-31 14:46:31

标签: macos swift2 keypress nstextview

我在swift中为macOS编写代码(所以我使用的是AppKit,而不是UIKit)。 我有一个不可编辑的NSTextView。 我想模仿一种终端。 以下代码了解用户何时按RETURN并打印“>> \ n”。我希望能够在用户按任意键时收到通知,以便写入相应的密钥。例如,如果用户按BACKSPACE,我将删除NSTextView中的一个字符,除非“>>”将被删除。

这是代码。     导入Cocoa

class ViewController: NSViewController {
    @IBOutlet var console: Console!

    override func viewDidLoad() {
        super.viewDidLoad()

        console.parent = self
        }

        func newLine() {
            let textStorage = console.textStorage
            if(textStorage != nil) {
                let myString = "\n>>"
                let myAttribute = [ NSForegroundColorAttributeName: NSColor.greenColor(), NSFontAttributeName: NSFont(name: "Menlo Regular", size: 13.0)! ]
                let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)

                textStorage!.appendAttributedString(myAttrString)
                let length = console.string!.characters.count

                console.setSelectedRange(NSRange(location: length,length: 0))
                console.scrollRangeToVisible(NSRange(location: length,length: 0))
            }
        }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

class Console : NSTextView {
    var parent: ViewController?
    override func insertNewline(sender: AnyObject?) {
        parent!.newLine()
    }

    override func controlTextDidBeginEditing(obj: NSNotification) {
        NSLog("wow") //unfortunately this method is never called, even setting the NSTextView as Editable
    }
}

相关问题:How to capture user input in real time in NSTextField?

1 个答案:

答案 0 :(得分:1)

您可以覆盖NSTextView的keyDown(with event: NSEvent)以进行常规按键操作。并检查event.charactersIgnoringModifiersevent.modifierFlags以了解按下了哪个键。

相关问题