【问题标题】:Subviews out of bounds of NSScrollView respond to mouse eventNSScrollView 越界子视图响应鼠标事件
【发布时间】:2015-12-22 21:14:27
【问题描述】:

我的问题是我的滚动视图的子视图即使不可见(超出滚动视图可见部分的范围)也会响应鼠标事件。

我有这个架构:

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

【问题讨论】:

    标签: events subview bounds nsscrollview


    【解决方案1】:

    我终于找到了问题。

    我需要在方法中添加选项 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。

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 1970-01-01
      • 2016-07-08
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多