您可以在NSView
子類中重寫updateTrackingAreas
來完成此行爲:
接口
@interface HoverView : NSView
@property (strong, nonatomic) NSColor *hoverColor;
@end
實施
@interface HoverView()
@property (strong, nonatomic) NSTrackingArea *trackingArea;
@property (assign, nonatomic) BOOL mouseInside;
@end
@implementation HoverView
- (void) drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Draw a white/alpha gradient
if (self.mouseInside) {
[_hoverColor set];
NSRectFill(self.bounds);
}
}
- (void) updateTrackingAreas {
[super updateTrackingAreas];
[self ensureTrackingArea];
if (![[self trackingAreas] containsObject:_trackingArea]) {
[self addTrackingArea:_trackingArea];
}
}
- (void) ensureTrackingArea {
if (_trackingArea == nil) {
self.trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
options:NSTrackingInVisibleRect | NSTrackingActiveAlways | NSTrackingMouseEnteredAndExited
owner:self
userInfo:nil];
}
}
- (void) mouseEntered:(NSEvent *)theEvent {
self.mouseInside = YES;
}
- (void) mouseExited:(NSEvent *)theEvent {
self.mouseInside = NO;
}
- (void) setMouseInside:(BOOL)value {
if (_mouseInside != value) {
_mouseInside = value;
[self setNeedsDisplay:YES];
}
}
@end