あなたはこの動作を達成するために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