Search code examples
objective-ccocoamouseeventmousehover

How to detect mouse hover on NSButton. Obj-C, Cocoa


I have a Mac application that has two NSButtons on each bottom corner of the window. I have set their Alpha = .5 in the .xib. I want to know how to detect a mouse hover over the button and change the alpha to lets say .9. How do I do this? I suppose all you need to know from my code is the .h.

@property (unsafe_unretained) IBOutlet NSButton *leftButton;
@property (unsafe_unretained) IBOutlet NSButton *rightButton;

Those are synthesized in my .m. Deployment target is OS X 10.6+. Thanks.

EDIT

I really haven't tried anything. I have seen something on NSTrackingArea, but am not positive on how to use it, more importantly, I was wondering if there was another way to go about it. Such as an event that is already called or something.


Solution

  • You need to Subclass the NSButton class (or even better the NSButtonCell class).

    - (void)mouseEntered:(NSEvent *)theEvent;
    - (void)mouseExited:(NSEvent *)theEvent;
    

    They should get called when the mouse enter and exit the area. You may also need to re create the tracking area, look here:

    - (void)updateTrackingAreas
    

    For fade in and fade out effect I played with animator and alpha value for example:

    [[self animator]setAlphaValue:0.9]; 
    

    EDIT: This is just for reference, so that you can take some ideas

    @interface MyButton : NSButton {
    - (void)mouseEntered:(NSEvent *)theEvent;
    - (void)mouseExited:(NSEvent *)theEvent;     
    - (void)updateTrackingAreas;
    @end