【问题标题】:Cocoa button rollovers with mouseEntered: and mouseExited:?带有 mouseEntered: 和 mouseExited: 的 Cocoa 按钮翻转
【发布时间】:2011-10-25 12:41:27
【问题描述】:

为了在按钮上创建翻转效果,我创建了一个名为 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”(当然也看不到图像更改)? ?可悲的是,我知道我遗漏了一些明显的东西,但我只是没有看到它...... ???

【问题讨论】:

    标签: objective-c cocoa


    【解决方案1】:

    问题在于,只有将自定义 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];
    }
    

    希望对你有帮助。

    【讨论】:

    • 你需要调用 [self setNeedsDisplay:YES];
    • Lloyd18,你是摇滚明星!奇迹般有效!谢谢。
    • 事实上,这非常愚蠢。我添加了 NSTrackingEnabledDuringMouseDrag 到我的,以确保在拖入和拖出该区域时翻转行为仍然。
    【解决方案2】:

    虽然设置跟踪区域绝对是一种方法,但NSButton/NSButtonCell 已经内置了此功能。

    查看 NSButton 的 showsBorderOnlyWhileMouseInside,以及对应的 NSButtonCell 的 mouseEnteredmouseExited。它记录在这里:

    https://developer.apple.com/documentation/appkit/nsbuttoncell/1527903-showsborderonlywhilemouseinside

    根据您的用例,这可能有效,也可能无效。对我来说,无论如何我都在继承 NSButtonCell,所以它是完美的。需要注意的一件事是它也会影响对drawBezel 的调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-31
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2015-05-25
      相关资源
      最近更新 更多