objective-c - NSButton 子类用于更改按钮图像

标签 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 事件期间图像没有返回到其原始状态有什么想法吗?

最佳答案

您实际上不必子类化 NSButton 来完成此任务。它可以在您的 XIB 文件中轻松完成。在 Interface Builder 属性检查器中,选择按钮并将 Type 设置为 Momentary Change,然后在 Image 下输入 buttonicon > 和 Alternate 下的 buttonicon2

关于objective-c - NSButton 子类用于更改按钮图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439831/

相关文章:

objective-c - tableview,更改焦点 tvos 的字体颜色

iphone - 使用NSPredicate删除对象

Python 诅咒 getmouse 函数?

cocoa - 大纲 View 中的鼠标事件

java - jSplitPane 当鼠标悬停时显示和隐藏左 Pane

iphone - 使用 iPhone 相机

iphone - 向表中插入数据时出现问题

objective-c - 在 objective-c 中声明属性和 @property 之间的区别

ios - NSMutableArray 与 NSDictionary 到 NSMutableDictionary

ios - UIBezierPath 和 NSBezierPath 在绘制圆弧时产生不同的结果