使用mouseEntered的可可按钮翻转:和mouseExited:?

gla*_*ish 10 cocoa objective-c

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

Button.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
Run Code Online (Sandbox Code Playgroud)

Button.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
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,每次我点击一个按钮,我在日志中看到"mouseDown",但我没有看到"mouseEntered"或"mouseExited"(当然看不到图像更改)?? 可悲的是,我知道我错过了一些明显的东西,但我只是没有看到它...... ???

Llo*_*d18 23

问题是只有在将自定义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];
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.