2017-09-24 168 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

非常感谢,这个作品很棒 –