2017-09-24 165 views
0

我在我的應用程序中有一個keyDown函數,用於捕獲名爲textInputNSTextView的輸入。有些轉換是通過將NSAttributedString追加到NSTextView中的輸入完成的。keyDown不立即更新NSTextView

目前工作正常,但我的問題是輸入到keyDown的文本框中的值不會被添加到textInput.textStorage?.string,直到按下另一個鍵。

例如,如果我輸入文字abcde而已進入textInput,然後裏面func keyDown()我嘗試訪問textInput.textStorage?.string,它將返回abcd

這裏是沒有多餘部分的功能:

override func keyDown(with event: NSEvent) { 
    let bottomBox = textInput.textStorage?.string // This returns one character short of what is actually in the text box 

    if let bottomBox = bottomBox { 
     var attribute = NSMutableAttributedString(string: bottomBox) 

     // Do some stuff here with bottomBox and attribute 

     // Clear and set attributed string 
     textInput.textStorage?.mutableString.setString("") 
     textInput.textStorage?.append(attribute) 
    } 
} 

如果我使用keyUp,這不是一個問題,雖然與keyUp的問題是,如果用戶按住鍵,屬性在NSAttributedString上不要設置,直到用戶釋放密鑰。

雖然也許有一種方法可以在keyDown函數中以編程方式釋放keyDown事件,或者生成keyUp事件,但似乎無法找到任何東西。

有沒有辦法解決這個問題?

+0

「我的應用程序中有一個keyDown函數」究竟在哪裏? –

+0

在監視keyDown事件的視圖控制器中 –

+0

不要使用NSEvent。使用通知。 –

回答

1

我喜歡做的是使用Cocoa綁定與屬性觀察員。設置您的屬性,像這樣:

class MyViewController: NSViewController { 
    @objc dynamic var textInput: String { 
     didSet { /* put your handler here */ } 
    } 

    // needed because NSTextView only has an "Attributed String" binding 
    @objc private static let keyPathsForValuesAffectingAttributedTextInput: Set<String> = [ 
     #keyPath(textInput) 
    ] 
    @objc private var attributedTextInput: NSAttributedString { 
     get { return NSAttributedString(string: self.textInput) } 
     set { self.textInput = newValue.string } 
    } 
} 

現在你的文本視圖與「不斷更新值」複選框綁定到attributedTextInput檢查:

enter image description here

的Et瞧,你的財產將被立即更新每次你輸入一個角色,你的財產didSet將立即被調用。

+0

非常感謝,這個作品很棒 –