Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa Button that will light up with mouse over

Is there a flag that can be set that will cause a Cocoa button to be highlighted when it is moused over. I need to this programatically with objective C on OSX.

like image 326
Mike2012 Avatar asked Nov 09 '09 23:11

Mike2012


2 Answers

Setup a tracking area for the view with addTrackingArea (provided you are using Leopard or newer OS X). You'll get events on mouse enter and mouse exit.

like image 198
Pablo Santa Cruz Avatar answered Nov 04 '22 19:11

Pablo Santa Cruz


something below maybe the answer.

class HoverButton: NSButton{

var backgroundColor: NSColor?
var hoveredBackgroundColor: NSColor?
var pressedBackgroundColor: NSColor?

private var hovered: Bool = false

override var wantsUpdateLayer:Bool{
    return true
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.commonInit()
}

override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)
    self.commonInit()
}

func commonInit(){
    self.wantsLayer = true
    self.createTrackingArea()
    self.hovered = false
    self.hoveredBackgroundColor = NSColor.selectedTextBackgroundColor()
    self.pressedBackgroundColor = NSColor.selectedTextBackgroundColor()
    self.backgroundColor = NSColor.clearColor()
}

private var trackingArea: NSTrackingArea!
func createTrackingArea(){
    if(self.trackingArea != nil){
        self.removeTrackingArea(self.trackingArea!)
    }
    let circleRect = self.bounds
    let flag = NSTrackingAreaOptions.MouseEnteredAndExited.rawValue + NSTrackingAreaOptions.ActiveInActiveApp.rawValue
    self.trackingArea = NSTrackingArea(rect: circleRect, options: NSTrackingAreaOptions(rawValue: flag), owner: self, userInfo: nil)
    self.addTrackingArea(self.trackingArea)
}

override func mouseEntered(theEvent: NSEvent) {
    self.hovered = true
    NSCursor.pointingHandCursor().set()
    self.needsDisplay = true
}

override func mouseExited(theEvent: NSEvent) {
    self.hovered = false
    NSCursor.arrowCursor().set()
    self.needsDisplay = true
}

override func updateLayer() {
    if(hovered){
        if (self.cell!.highlighted){
            self.layer?.backgroundColor = pressedBackgroundColor?.CGColor
        }
        else{
            self.layer?.backgroundColor = hoveredBackgroundColor?.CGColor
        }
    }
    else{
        self.layer?.backgroundColor = backgroundColor?.CGColor
    }
}

}

link: https://github.com/fancymax/HoverButton

like image 40
Fancy Max Avatar answered Nov 04 '22 19:11

Fancy Max