如何快速捕获NSControl上的一些事件 [英] How to catch some events on a NSControl in swift
问题描述
我正在Swift中为OSX编写一个应用程序,我正在寻找一种捕捉NSControl事件的好方法. 显然,我进行了搜索,但发现的信息通常不清楚或过旧. 以我为例,我想在NSTextField上捕获几个事件(键输入,文本更改,焦点丢失等).
I am writing an application for OSX in Swift and I am looking for a good way to catch events on a NSControl. Obviously, I searched but the informations I found are often unclear or old. In my case, I would like to catch several events on a NSTextField (key up, text changed, focus lost,...).
当我在NSTextField中按下"Enter"时,它会发送一个动作.当我单击或在NSTextField中书写时,也许有一种发送动作的方法吗?
When I push on "Enter" in the NSTextField, it sends an action. Maybe is there a way to send an action when I click or write in the NSTextField?
推荐答案
您可以将NSTextField子类化,并覆盖textDidChange
进行文本更改,重写textDidEndEditing以获得丢失的焦点,并使用keyUp方法进行举起.尝试这样:
You can subclass NSTextField and override textDidChange
for text change, textDidEndEditing for lost focus and keyUp method for key up. Try like this:
import Cocoa
class CustomTextField: NSTextField {
override func viewWillMove(toSuperview newSuperview: NSView?) {
// customize your field here
frame = newSuperview?.frame.insetBy(dx: 50, dy: 50) ?? frame
}
override func textDidChange(_ notification: Notification) {
Swift.print("textDidChange")
}
override func textDidEndEditing(_ notification: Notification) {
Swift.print("textDidEndEditing")
}
override func keyUp(with event: NSEvent) {
Swift.print("keyUp")
}
}
View Controller示例用法:
View Controller sample Usage:
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textField = CustomTextField()
view.addSubview(textField)
}
}
这篇关于如何快速捕获NSControl上的一些事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!