gpt4 book ai didi

objective-c - NSButton NSTrackingArea - 跟踪不起作用

转载 作者:行者123 更新时间:2023-12-03 16:21:32 26 4
gpt4 key购买 nike

我正在尝试完成鼠标悬停事件上突出显示的按钮。所以我对 NSButton 进行了子类化,其中放置了 NSTrackingArea 和方法 - (void)mouseEntered:(NSEvent *)event- (void)updateTrackingAreas

按钮的创建看起来是这样的(它在循环中,所以我使用数组来收集):

        CalendarTile *button = [[CalendarTile alloc] init];

[button setFrame:CGRectMake(point_x, point_y, button_frame_width, button_frame_height)];
[button setBordered:NO];
[button setBezelStyle:NSRegularSquareBezelStyle];
[button setButtonType:NSMomentaryChangeButton];
[button setFont:[NSFont fontWithName:@"Avenir Next" size:40]];
[button setAlignment:NSCenterTextAlignment];

[button setTitle:[NSString stringWithFormat:@"%i", i]];
[button setTextColor:[NSColor colorWithCalibratedRed:(float)62/255 green:(float)62/255 blue:(float)62/255 alpha:1.0]];

[arrayWithButtons addObject:button];

...

for (CalendarTile *btn in arrayWithButton) {
[self addSubview:btn];
}

这是一个子类 - CalendarTile.m:

@implementation CalendarTile
- (void)updateTrackingAreas
{
[super updateTrackingAreas];

if (trackingArea)
{
[self removeTrackingArea:trackingArea];
}

NSTrackingAreaOptions options = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
}

- (void)mouseEntered:(NSEvent *)event
{
[self setImage:[NSImage imageNamed:@"highlight.png"]];
NSLog(@"HIGHLIGHT");
}

当我将鼠标悬停在日志上时,它应该在日志中显示“HIGHLIGHT” - 遗憾的是没有。

你能帮我吗?我做错了什么?

最佳答案

这是我完美地为我创建和工作的......

第 1 步:创建带有跟踪区域的按钮

 NSButton *myButton = [[NSButton alloc] initWithFrame:NSMakeRect(100, 7, 100, 50)];
[myButton setTitle:@"sample"];

[self.window.contentView addSubview:myButton];
// Insert code here to initialize your application
NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
initWithRect:[myButton bounds]
options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
owner:self userInfo:nil];
[myButton addTrackingArea:trackingArea];

步骤:2 实现以下方法

- (void)mouseEntered:(NSEvent *)theEvent{
NSLog(@"entered");
[[myButton cell] setBackgroundColor:[NSColor blueColor]];


}

- (void)mouseExited:(NSEvent *)theEvent{
[[myButton cell] setBackgroundColor:[NSColor redColor]];
NSLog(@"exited");

}

关于objective-c - NSButton NSTrackingArea - 跟踪不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12436327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com