【问题标题】:Swift: How to determine which control was clicked on mouseDownSwift:如何确定在 mouseDown 上单击了哪个控件
【发布时间】:2019-05-05 21:20:52
【问题描述】:

我试图在(Cocoa with Storyboards)应用程序窗口中的某些控件上捕获鼠标按下事件。

如果我在 ViewController 类中覆盖 mouseDown(with event: NSEvent),我将面临两个问题:

  1. 无法(直接)识别窗口中的哪个控件已被单击。为此,我使用以下内容:

斯威夫特 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)。 我是否遗漏了什么,或者这是捕获和处理鼠标按下事件的方法?

  1. 对于某些控件,例如NSLevelIndicator,我的重写方法没有被调用。为什么?

【问题讨论】:

  • 控件是NSControl的子类吗?控件是否处理 mouseDown 事件?
  • 是的,我尝试使用源自NSCotrol 的控件,例如NSTextFieldNSLevelIndicator。但是,我无法为一个或一组控件定义 mouseDown 处理程序(在这种情况下,我希望有某种方法来区分调用了该处理程序的对象)。我不确定你对第二个问题的意思。
  • 看看NSClickGestureRecognizer

标签: swift cocoa mouseevent appkit


【解决方案1】:

你必须重写 NSView mouseDown,而不是 NSViewController mouseDown。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多