2013-01-31 5 views
9

NSCollectionViewがありますが、その中に数個のNSViewがあります。 NSViewにはNSBoxがあり、選択すると色が変わります。私はまた覆われたときにNSBox色を変えたいと思う。NSCollectionViewのホバーオーバーエフェクト

サブクラスNSBoxには、mouseEnteredmouseExitedのメソッドが追加されています。私はをviewWillMoveToWindowの内側に使用しましたが、問題は、ボックスが入っているサブビューを最初に選択した場合にのみ発生します。

さらに、選択されたボックスにはホバーオーバー効果が発生します。 NSCollectionViewのすべてのNSViewがすぐにその効果を示すように、ホバーオーバーエフェクトを実装するにはどうすればよいですか?

答えて

2

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