Вопрос

I have a borderless NSButton that contains an image and is subclassed with my ButtonEffect class to detect mouseEntered and mouseExited events. My goal is to have just the edge of the image glow as the mouse enters the button area. I know I can achieve this by using two different images (one with shadow and another without) but I need to do this with one image.

Here's an example of what I hope to achieve for the mouseEntered event: mouse entered button area

And here's what it should look after the cursor leaves the button area: mouse exited button area

Here's my attempt by setting the background of the cell but it changes the color of the entire button area.

#import "ButtonEffect.h"

@interface ButtonEffect ()

@property NSTrackingArea *trackingArea;

@end

@implementation ButtonEffect

- (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 {
    [[NSCursor pointingHandCursor] set];
    [self.cell setBackgroundColor:NSColor.redColor];
    NSLog(@"mouse entered button");
}

- (void)mouseExited:(NSEvent *)event {
    [[NSCursor arrowCursor] set];
    [self.cell setBackgroundColor:nil];
    NSLog(@"mouse exited button");
}

@end
Это было полезно?

Решение

You want something like this?

     - (void)mouseEntered:(NSEvent *)event {
    CALayer *lay=[btn layer];
    CGColorRef myColor=CGColorCreateGenericRGB(1, 1, 1, 1);
    CGColorRelease(myColor);
    myColor=CGColorCreateGenericRGB(0, 0, 0.8, 1);
    [lay setBorderColor:myColor];
    [lay setBorderWidth:1];
    [btn setWantsLayer:YES];
    [btn setLayer:lay];
    CGColorRelease(myColor);

}

- (void)mouseExited:(NSEvent *)event {
    CALayer *lay=[btn layer];
    CGColorRef myColor=CGColorCreateGenericRGB(1, 1, 1, 1);
    CGColorRelease(myColor);
    myColor=CGColorCreateGenericRGB(0, 0, 0.8, 1);
    [lay setBorderColor:myColor];
    [lay setBorderWidth:0];
    [btn setWantsLayer:YES];
    [btn setLayer:lay];
    CGColorRelease(myColor);

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top