3

我有一个无边框NSButton(或多或少NSTextField带有动作),我希望它的行为类似于“基于图像”的按钮,即我希望按钮文本在用鼠标传递并单击时改变颜色。有没有简单的方法来实现这一目标?

这是我的按钮初始化上下文:

    NSButton* but =[[NSButton alloc] initWithFrame:NSMakeRect(5, 5, 125, 25)] ;
    [but setTitle:@"Do not show Again"];
    [but setButtonType:NSMomentaryLightButton]; //I figure it could be here
    [but setBezelStyle:NSHelpButtonBezelStyle];
    [but setBordered:NO];
    [but setAction:@selector(writeToUserDefaults)];
    [but setFont:[NSFont fontWithName:@"Arial" size:9.0]];
    [self.view addSubview:but];

无效的来源:无边框 NSButton 变灰

我的解决方案是什么(除了子类化 NSButton ?)

4

1 回答 1

3

解决方案是使用 Apple 文档中的 NSTrackingArea

An NSTrackingArea object defines a region of view that generates mouse-tracking and cursor-update events when the mouse is over that region.

在您的情况下,您需要针对 NSButton 的框架设置跟踪区域,并在收到鼠标跟踪事件时更改文本颜色。

- (void)awakeFromNib:(NSWindow *)newWindow 
{
    NSButton* but =[[NSButton alloc] initWithFrame:NSMakeRect(5, 5, 125, 25)] ;
    [but setTitle:@"Do not show Again"];
    [but setBezelStyle:NSHelpButtonBezelStyle];
    [but setBordered:NO];
    [but setAction:@selector(writeToUserDefaults)];
    [but setFont:[NSFont fontWithName:@"Arial" size:9.0]];
    [self.view addSubview:but];

    NSTrackingArea* trackingArea = [[NSTrackingArea alloc] initWithRect:[but frame] 
                                                                options:(NSTrackingInVisibleRect | NSTrackingEnabledDuringMouseDrag | NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways) 
                                                                  owner:self userInfo:nil];

[self.view addTrackingArea:trackingArea];
}

- (void) mouseEntered:(NSEvent*)theEvent {
    //Set text color
}

- (void) mouseExited:(NSEvent*)theEvent {
    //Reset text color
}
于 2013-11-06T02:28:51.303 回答