Cocoa按钮使用mouseEntered:和mouseExited:? [英] Cocoa button rollovers with mouseEntered: and mouseExited:?

查看:312
本文介绍了Cocoa按钮使用mouseEntered:和mouseExited:?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In hopes of creating a rollover effect on a button, I created a subclass of NSButton called Button.

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

Button.m:
#import Button.h

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

时间我点击一个按钮,我在日志中看到mouseDown,但我没有看到mouseEntered或mouseExited(当然没有看到图像改变)。可悲的是,我知道我缺少一些明显的东西,但我只是没有看到它... ???

With the code above, every time I click on a button I see "mouseDown" in the logs, but I don't see "mouseEntered" nor "mouseExited" (and of course don't see the image change)?? Sadly, I know I'm missing something obvious, but I'm just not seeing it... ???

推荐答案

问题是NSButton只能在你添加自定义NSTrackingArea到按钮时处理一些鼠标事件。

The problem is that NSButton can handle some mouse events only if you add your custom NSTrackingArea to button.

尝试在你的按钮类中添加这个代码。它帮助了我。如果他们不满意你也可以玩选项。

Try to add this code in your button class. It helped me. Also you can play with options if they not satisfied you.

- (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];
}

希望它有帮助。

这篇关于Cocoa按钮使用mouseEntered:和mouseExited:?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆