Search code examples
macoscocoaeventsmousensbutton

How to change NSButton's title when cursor is on it


I'm beginner of Cocoa Programming. How can I change NSButton's title when cursor is on the button? (without clicking).


Solution

  • If you look at the class hierarchy for NSButton you'll see that it derives from NSResponder which is the class that handles mouse events.

    https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nsbutton_Class/Reference/Reference.html

    Create a subclass of NSButton and override the following messages to set the title to what you want:

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

    Add this to your initializer (Either awakeFromNib or your init message, depending on your usage):

    [self addTrackingRect:[self bounds] owner:self userData:NULL assumeInside:YES];
    

    Note that even when the mouse has not actually entered the tracking area the first time the title will display the exited message. You may want to add some state to your class to if you want a third title set before it enters the tracking area the first time.

    EDIT: Maybe this will help.

    Here is the header file "MyButton.h":

    #import <Cocoa/Cocoa.h>
    
    @interface MTButton : NSButton {
        NSTrackingRectTag myTrackingRectTag;
    }
    
    @end
    

    Pretty standard stuff.

    Here is my source file.

    #import "myButton.h"
    
    
    @implementation MTButton
    
    - (void) awakeFromNib
    {
        [self setTitle:@"Initial"];
        myTrackingRectTag = [self addTrackingRect:[self bounds]
                                            owner:self
                                         userData:NULL
                                     assumeInside:YES];
    
    }
    
    - (void) dealloc
    {
        [super dealloc];
        [self removeTrackingRect:myTrackingRectTag];
    }
    
    
    - (void)mouseEntered:(NSEvent *)theEvent
    {   
        [super mouseEntered:theEvent];
    
        [self setTitle:@"Entered"];
    }
    
    - (void)mouseExited:(NSEvent *)theEvent
    {
        [super mouseExited:theEvent];
    
        [self setTitle:@"Exited"];
    }
    
    @end