【问题标题】:How can I change an IBAction to mouseEntered? [closed]如何将 IBAction 更改为 mouseEntered? [关闭]
【发布时间】:2020-01-05 03:15:48
【问题描述】:

我想在鼠标进入 NSButton 时创建 IBAction。每当我从按钮创建 IBAction 时,它仅在我单击它时才起作用。

我怎样才能使 IBActions 在我的鼠标进入按钮时工作?

【问题讨论】:

    标签: swift macos cocoa ibaction


    【解决方案1】:

    您可以子类化您的按钮单元并将其属性showsBorderOnlyWhileMouseInside 设置为true。然后你可以简单地覆盖mouseEntered 方法:

    import Cocoa
    
    class ButtonCell: NSButtonCell {
        override func awakeFromNib() {
            super.awakeFromNib()
            showsBorderOnlyWhileMouseInside = true
        }
        override func mouseEntered(with event: NSEvent) {
            super.mouseEntered(with: event)
            print(#function)
        }
        override func mouseExited(with event: NSEvent) {
            super.mouseExited(with: event)
            print(#function)
        }
    }
    

    如果您不想将showsBorderOnlyWhileMouseInside 设置为true,另一种选择是继承NSButton 并为其添加跟踪区域。您需要将您的ButtonCell 作为所有者传递:

    import Cocoa
    
    class Button: NSButton {
        override func awakeFromNib() {
            super.awakeFromNib()
            addTrackingArea(.init(rect: bounds, options: [.activeInKeyWindow, .mouseEnteredAndExited], owner: cell as! ButtonCell, userInfo: nil))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2013-07-21
      • 2015-05-05
      • 2016-08-15
      • 2018-01-02
      • 2020-11-02
      相关资源
      最近更新 更多