Simple mouseover effect on NSButton

后端 未结 7 688
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:11

    Swift 3:

    Create the button with code or just use it's @IBOutlet. Then define the button's tracking area for mouse over (hover):

    let area = NSTrackingArea.init(rect: yourButtonName.bounds,
                                   options: [.mouseEnteredAndExited, .activeAlways], 
                                   owner: self, 
                                   userInfo: nil)
    yourButtonName.addTrackingArea(area)
    

    Then override mouseEntered and mouseExited, set whatever you want to change (button color, button image, button text,..) in these functions:

    override func mouseEntered(with event: NSEvent) {
        print("Entered: \(event)")
    }
    
    override func mouseExited(with event: NSEvent) {
        print("Exited: \(event)")
    }
    

    If you have multiple buttons (with tracking area added for each) and you need to identify which button triggered the mouseEntered event, you can add some userInfo information for this purpose, so instead of:

    userInfo: nil
    

    Add your custom button name in userInfo for each button, for example:

    userInfo: ["btnName": "yourButtonName"]
    

    Then you can write a switch-case or if statements in your mouseEntered and mouseExited functions like this:

    override func mouseEntered(with event: NSEvent) {
            // Identify which button triggered the mouseEntered event
            if let buttonName = event.trackingArea?.userInfo?.values.first as? String {
                switch (buttonName) {
                case "yourButtonName":
                    //do whatever you want for this button..
                case "anotherButtonName":
                    //do whatever you want for this button..
                default:
                    print("The given button name: \"\(buttonName)\" is unknown!")
                }
            }
        }
    

提交回复
热议问题