【发布时间】:2019-05-05 21:20:52
【问题描述】:
我试图在(Cocoa with Storyboards)应用程序窗口中的某些控件上捕获鼠标按下事件。
如果我在 ViewController 类中覆盖 mouseDown(with event: NSEvent),我将面临两个问题:
- 无法(直接)识别窗口中的哪个控件已被单击。为此,我使用以下内容:
斯威夫特 4:
override func mouseDown(with event: NSEvent)
{
let point: NSPoint = event.locationInWindow
let view: NSView = self.view.hitTest(point)!
if type(of:view) == NSTextField.self // with tags is also fine
{
// do something with the control (in the example NSTextField)
// (view as! NSTextField).backgroundColor = NSColor.systemPink
}
}
我有点疑惑,为什么对于这样一个基本的 GUI 操作,没有为鼠标单击提供的“本机”事件处理程序(通过创建 @IBAction)。
我是否遗漏了什么,或者这是捕获和处理鼠标按下事件的方法?
- 对于某些控件,例如
NSLevelIndicator,我的重写方法没有被调用。为什么?
【问题讨论】:
-
控件是
NSControl的子类吗?控件是否处理 mouseDown 事件? -
是的,我尝试使用源自
NSCotrol的控件,例如NSTextField,NSLevelIndicator。但是,我无法为一个或一组控件定义mouseDown处理程序(在这种情况下,我希望有某种方法来区分调用了该处理程序的对象)。我不确定你对第二个问题的意思。 -
看看
NSClickGestureRecognizer。
标签: swift cocoa mouseevent appkit