超出NSScrollView范围的子视图会响应鼠标事件

时间:2015-12-22 21:14:28

标签: events subview bounds nsscrollview

我的问题是我的scrollView的子视图响应鼠标事件,即使它们不可见(在scrollView的可见部分的边界之外)。

我有这个架构:

CustomView *view01 = [[CustomView alloc] init];
CustomView *view02 = [[CustomView alloc] init];

NSView *contentView = [[NSView alloc] init];
[contentView addSubview:view01];
[contentView addSubview:view02];

NSSCrollView *scrollView = [[NSScrollView alloc] init];
scrollView setDocumentView:contentView];

使用CustomView实现:

#import "CustomView.h"

@interface CustomView ()
{
    NSTrackingArea *trackingArea;
}
@end

@implementation CustomView

-(id)initWithFrame:(NSRect)contentRect
{
    if(self = [super initWithFrame:(NSRect)contentRect])
    {
        [self setFrame:contentRect];
    }

    return self;
}


- (void)mouseDown: (NSEvent*)event
{
    NSLog(@"mouseDown:");

    [NSApp preventWindowOrdering];
}

- (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)evt
{
    return YES;
}


-(BOOL)acceptsFirstResponder
{
    return YES;
}

-(void)updateTrackingAreas
{
    if(trackingArea != nil)
    {
        [self removeTrackingArea:trackingArea];
    }

    int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways);
    trackingArea = [ [NSTrackingArea alloc] initWithRect:[self bounds]
                                             options:opts
                                               owner:self
                                            userInfo:nil];
    [self addTrackingArea:trackingArea];
}


- (void)mouseEntered:(NSEvent *)theEvent
{
    NSLog(@"mouseEntered:");
}

- (void)mouseExited:(NSEvent *)theEvent
{
    NSLog(@"mouseExited:");
}


- (NSView *)hitTest:(NSPoint)aPoint
{
    return NSPointInRect(aPoint, self.frame) ? self : nil;
}

@end

1 个答案:

答案 0 :(得分:0)

我终于找到了问题。

我需要在方法中添加选项NSTrackingInVisibleRect:

-(void)updateTrackingAreas
{
    if(trackingArea != nil)
    {
        [self removeTrackingArea:trackingArea];
    }

    int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways| NSTrackingInVisibleRect);

    trackingArea = [ [NSTrackingArea alloc] initWithRect:[self bounds]
                                         options:opts
                                           owner:self
                                        userInfo:nil];
    [self addTrackingArea:trackingArea];
}

然后,当CustomView的一部分在scrollView之外时,它不会响应mouseEntered和mouseExited。