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 - Web服务应用程序的设计模式(使用APNS)

c++ - 为 iPhone 应用程序解析 RSS/Atom 提要的最佳方法是什么?

swift - MacOS:识别键入的 NSMenuItem 快捷方式或按下鼠标

iphone - 在代码或数据库中传播删除?

cocoa - 如何检查 NSPoint 是否位于 NSRect 内

c# - 如何在 TeeChart for .net 中添加鼠标点击事件

javascript - 鼠标事件到 ipad 兼容性的触摸事件

ios - 如果用户以编程方式点击 UITextfield,如何显示 UIDatePicker

objective-c - 在 Objective-C 编程中具有单个键的 NSMutableDictionary 包含多个值

python-3.x - Win32 鼠标点击