objective-c – 可可按钮滚动与mouseEntered:和mouseExited:?

前端之家收集整理的这篇文章主要介绍了objective-c – 可可按钮滚动与mouseEntered:和mouseExited:?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
希望在按钮上创建一个翻转效果,我创建了一个名为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

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”(当然看不到图像的变化)?可悲的是,我知道我错过了一些明显的东西,但我只是没有看到它?

解决方法

问题是NSButton只有在您将自定义NSTrackingArea添加到按钮时才能处理某些鼠标事件.

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

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

希望它有帮助.

原文链接:https://www.f2er.com/c/112514.html

猜你在找的C&C++相关文章