cocoansbuttonnsbuttoncell

Simple mouseover effect on NSButton


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,


Solution

  • 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");
    
    }