objective-c - 使用 mouseEntered 的 Cocoa 按钮翻转 : and mouseExited:?

标签 objective-c cocoa

为了在按钮上创建翻转效果,我创建了一个名为 Button 的 NSButton 子类。

按钮.h:

#import <AppKit/AppKit.h>

@interface Button : NSButton {
}

- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;
- (void)mouseDown:(NSEvent *)ev;
- (void)mouseUp:(NSEvent *)theEvent;

@end

按钮.m: #import "Button.h"

@implementation Button

- (id)initWithFrame:(NSRect)frameRect  {
    self = [super initWithFrame:frameRect];
    if(self != nil) {
    NSLog(@"btn init");
}
    return self;
}


- (void)mouseEntered:(NSEvent *)theEvent{
    NSLog(@"mouseEntered");
    [self setImage:[NSImage imageNamed:@"lockIcon_2.png"]];
    [self setNeedsDisplay];
}
- (void)mouseExited:(NSEvent *)theEvent{
    [self setImage:[NSImage imageNamed:@"lockIcon_1.png"]];
    NSLog(@"mouseExited");  
    [self setNeedsDisplay];
}

- (void)mouseDown:(NSEvent *)ev {
    NSLog(@"mouseDown!");
}

- (void)mouseUp:(NSEvent *)ev {
    NSLog(@"mouseUp!");
}

@end

使用上面的代码,每次我点击一个按钮时,我都会在日志中看到“mouseDown”,但我没有看到“mouseEntered”或“mouseExited”(当然也没有看到图像变化)? ?可悲的是,我知道我遗漏了一些明显的东西,但我只是没有看到它......???

最佳答案

问题是,只有将自定义 NSTrackingArea 添加到按钮,NSButton 才能处理一些鼠标事件。

尝试将此代码添加到您的按钮类中。它帮助了我。如果您不满意,您也可以尝试选择。

- (void)createTrackingArea
{
    NSTrackingAreaOptions focusTrackingAreaOptions = NSTrackingActiveInActiveApp;
    focusTrackingAreaOptions |= NSTrackingMouseEnteredAndExited;
    focusTrackingAreaOptions |= NSTrackingAssumeInside;
    focusTrackingAreaOptions |= NSTrackingInVisibleRect;

    NSTrackingArea *focusTrackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
            options:focusTrackingAreaOptions owner:self userInfo:nil];
    [self addTrackingArea:focusTrackingArea];
}


- (void)awakeFromNib
{
    [self createTrackingArea];
}

希望对您有所帮助。

关于objective-c - 使用 mouseEntered 的 Cocoa 按钮翻转 : and mouseExited:?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7889419/

相关文章:

objective-c - 具有多个部分时使用 sectionIndexTitlesForTableView 进行索引

当 Swift 文件包含在框架中时,不会编译前缀项目文件头中的 Objective-C 宏

json - Cocoa - 解析 JSON 字符串

objective-c - 如何将 NSButton 插入 NSTextView 中? (排队)

objective-c - NSStream : Is there any airtight defense against blocking?

objective-c - 为 NSComboBox 项目设置工具提示

ios - 更新核心数据模型后出错 - 无法识别的选择器发送到实例

objective-c - 如何在 mac 中的 Objective-C 中计算应用程序和缓存内存,如事件监视器?

c++ - SDL 错误 Undefined symbols for architecture x86_64 "_SDL_main"

cocoa - NSDateFormatter 可以格式化相对于当前时间以外的时间的日期吗?