为了在按钮上创建翻转效果,我创建了一个名为 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/