第一步是設置視圖控制器是的NSTextField的委託。如果您使用筆尖或故事情節會是這樣的:
基本上Ctrl拖動查看器,並設置委託。
import Cocoa
class ViewController: NSViewController {
override func controlTextDidChange(obj: NSNotification) {
guard let textField = obj.object as? NSTextField else { return }
if textField.stringValue.characters.last == " " {
print(textField.stringValue.componentsSeparatedByString(" "))
}
}
}
它將打印出其中由空格隔開字的陣列:
然後,可以對文本反應在視圖控制器改變
[「一」,「」]
[ 「一」, 「男孩」, 「」]
[ 「一」, 「男孩」, 「來了」, 「」]
[ 「一」, 「男孩」, 「來了」, 「對」, 「」]
[ 「一」, 「男孩」, 「來了」, 「對」, 「學校」, 「」]
您可能需要最後一個項目從數組中刪除:
override func controlTextDidChange(obj: NSNotification) {
guard let textField = obj.object as? NSTextField else { return }
if textField.stringValue.characters.last == " " {
print(textField.stringValue.componentsSeparatedByString(" ").filter { $0 != "" })
}
}
對於NSTextView的邏輯是類似的。從文本視圖Ctrl拖動設置視圖控制器爲委託:
然後使用下面的代碼:
func textDidChange(obj: NSNotification) {
guard let textView = obj.object as? NSTextView else { return }
guard let stringValue = textView.textContainer?.textView?.string else { return }
if stringValue.characters.last == " " {
print(stringValue.componentsSeparatedByString(" ").filter { $0 != "" })
}
}
這將很好地工作:
你嘗試搜索?這可能會幫助你。 http://stackoverflow.com/questions/32446978/swift-capture-keydown-from-nsviewcontroller – Khundragpan