Simple mouseover effect on NSButton

后端 未结 7 690
Happy的楠姐
Happy的楠姐 2021-02-04 01:51

I am creating a custom NSButtonCell for a custom rendering.

Now, I want to have different aspect depending if the mouse is over the button or not. How can

相关标签:
7条回答
  • 2021-02-04 02:16

    Swift 5 version with callback, super easy to use:

    final class HoverButton: NSButton {
    
        private let callback: (HoverButton, Bool) -> Void
    
        init(callback: @escaping (HoverButton, Bool) -> Void) {
            self.callback = callback
            super.init(frame: .zero)
            let area = NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil)
            addTrackingArea(area)
        }
    
        @available(*, unavailable)
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func mouseEntered(with event: NSEvent) {
            super.mouseEntered(with: event)
            callback(self, true)
        }
    
        override func mouseExited(with event: NSEvent) {
            super.mouseExited(with: event)
            callback(self, false)
        }
    
    }
    

    Usage:

    let button = HoverButton { button, isHovered in
        button.animator().alphaValue = isHovered ? 1 : 0.5
    }
    
    0 讨论(0)
提交回复
热议问题