Simple mouseover effect on NSButton

AP. picture AP. · May 23, 2011 · Viewed 16.3k times · Source

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 I get this information?

Thanks and regards,

Answer

VSN picture VSN · Feb 25, 2014

Here is i have created and worked for me perfectly...

Step 1: Create the Button with tracking area

 NSButton *myButton = [[NSButton alloc] initWithFrame:NSMakeRect(100, 7, 100, 50)];
[myButton setTitle:@"sample"];

[self.window.contentView addSubview:myButton];
// Insert code here to initialize your application
NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
                                initWithRect:[myButton bounds]
                                options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
                                owner:self userInfo:nil];
[myButton addTrackingArea:trackingArea];

Step: 2 Implement the following methods

- (void)mouseEntered:(NSEvent *)theEvent{
NSLog(@"entered");
[[myButton cell] setBackgroundColor:[NSColor blueColor]];


}

- (void)mouseExited:(NSEvent *)theEvent{
[[myButton cell] setBackgroundColor:[NSColor redColor]];
NSLog(@"exited");

}