NSButton子类更改按钮图像

时间:2014-05-03 03:18:08

标签: objective-c cocoa mouseevent nsbutton nsbuttoncell

我将NSButton子类化,以便按钮图像在单击时会发生变化。以下代码用于子类。

#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

这是当前按钮。如您所见,按钮在单击mouseUp事件后不会返回其原始图像。

enter image description here

有关为什么在mouseUp事件期间图片未恢复到原始状态的任何想法?

1 个答案:

答案 0 :(得分:2)

你真的不必继承NSButton来实现这一目标。它可以在您的XIB文件中轻松完成。在Interface Builder属性检查器中,选择您的按钮并将Type设置为Momentary Change,然后在buttonicon下的Imagebuttonicon2下的Alternate下输入

相关问题