我有一个NSCollectionView
,里面有几个NSView
个。 NSView
中有一个NSBox
,在选中时会改变颜色。我还希望在悬停时使NSBox
更改颜色。
我已将NSBox
子类化,并添加了mouseEntered
和mouseExited
方法。我在addTrackingRect
中使用了viewWillMoveToWindow
,但问题是只有在我第一次选择框所在的子视图时才会悬停效果。
此外,只有选中的框会在其上发生悬停效果。如何实现悬停效果,以便我NSView
中的所有NSCollectionView
立即显示效果?
答案 0 :(得分:4)
您可以覆盖updateTrackingAreas
的子类中的NSView
来完成此行为:
<强>接口强>
@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
答案 1 :(得分:0)
雨燕5
var mouseInside : Bool = false { didSet {
needsDisplay = true
}}
@IBInspectable var hoverColor : NSColor = .controlAccentColor
var trackingArea : NSTrackingArea?
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if mouseInside {
hoverColor.setFill()
bounds.fill()
}
}
override func updateTrackingAreas() {
super.updateTrackingAreas()
ensureTrackingArea()
if let trackingArea = trackingArea, !trackingAreas.contains(trackingArea) {
addTrackingArea(trackingArea)
}
}
func ensureTrackingArea() {
if trackingArea == nil {
trackingArea = NSTrackingArea(rect: .zero,
options: [
.inVisibleRect,
.activeAlways,
.mouseEnteredAndExited],
owner: self,
userInfo: nil)
}
}
override func mouseEntered(with event: NSEvent) {
mouseInside = true
}
override func mouseExited(with event: NSEvent) {
mouseInside = false
}
}