Simple mouseover effect on NSButton

后端 未结 7 709
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:06

    This is a simple code to track mouse enter and mouse exit events on some controls (Images, Label, etc...):

    @IBOutlet weak var myImage: NSImageView!
    @IBOutlet weak var myLabel: NSTextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let area1 = myTrakingArea(control: self.myImage)
        let area2 = myTrakingArea(control: self.myLabel)
        self.myImage.addTrackingArea(area1)
        self.myLabel.addTrackingArea(area2)
    }
    
    func myTrakingArea(control: NSControl) -> NSTrackingArea {
        return NSTrackingArea.init(rect: control.bounds,
        options: [.mouseEnteredAndExited, .activeAlways],
        owner: control,
        userInfo: nil)
    }
    
    override func mouseEntered(with event: NSEvent) {
        if let owner = event.trackingArea?.owner as? NSControl {
            let id : String = owner.identifier!.rawValue
    
            switch id {
            case self.myLabel.identifier!.rawValue:
                    print("Entered Quit Label")
            case self.myImage.identifier!.rawValue:
                    print("Entered Quit Image")
                default:
                    print("Entered ???")
            }
        }
    }
    
    override func mouseExited(with event: NSEvent) {
        if let owner = event.trackingArea?.owner as? NSControl {
            let id : String = owner.identifier!.rawValue
    
            switch id {
            case self.myLabel.identifier!.rawValue:
                    print("Exited Quit Label")
            case self.myImage.identifier!.rawValue:
                    print("Exited Quit Image")
                default:
                    print("Exited ???")
            }
        }
    }
    

提交回复
热议问题