我在我的应用程序中有一个keyDown
函数,用于捕获名为textInput
的NSTextView
的输入。有些转换是通过将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事件,但似乎无法找到任何东西。
有没有办法解决这个问题?
“我的应用程序中有一个keyDown函数”究竟在哪里? –
在监视keyDown事件的视图控制器中 –
不要使用NSEvent。使用通知。 –