单击时自定义无边界NSButton行为?

时间:2013-11-05 21:57:55

标签: macos cocoa nsbutton

我有一个无边框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];

无效的来源:Borderless NSButton Turns Gray

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

1 个答案:

答案 0 :(得分: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
}