Question

I subclassed NSButton so that the button image would change when it is clicked. The following code is used for the subclass.

#import "MyImageButton2.h"

@interface MyImageButton2 ()

@property (strong, nonatomic) NSCursor *cursor;

@end

@implementation MyImageButton2

- (void)setImage:(NSImage *)image {

    [super setImage:image];

    if (!self.image) {
        self.image = [NSImage imageNamed:@"buttonicon"];
    }
}

- (void)mouseDown:(NSEvent *)theEvent {

    [super mouseDown:theEvent];

    self.image = [NSImage imageNamed:@"buttonicon2"];
}

- (void)mouseUp:(NSEvent *)theEvent {

    [super mouseUp:theEvent];

    self.image = [NSImage imageNamed:@"buttonicon"];
}

- (void)resetCursorRects {

    NSCursor *cursor = (self.cursor) ? self.cursor : [NSCursor pointingHandCursor];

    if (cursor) {
        [self addCursorRect:[self bounds] cursor:cursor];
    } else {
        [super resetCursorRects];
    }
}

@end

And here is the current button. As you can see, the button does not return to its original image after it is clicked, the mouseUp event.

enter image description here

Any ideas on why the image is not returned to its original state during the mouseUp event?

Was it helpful?

Solution

You don't really have to subclass NSButton to accomplish this. It can be easily done in your XIB file. In the Interface Builder property inspector, select your button and set the Type to Momentary Change and then enter buttonicon under Image and buttonicon2 under Alternate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top