macOS

Mac OS 中 监听鼠标滑动区域

2017-10-19  本文已影响7人  齐小益

前言

在iOS中,获取手指的触摸区域比较简单,可以通过手势,touchsBegin等一系列来判断。甚至还可以通过 hitTest去做很多花哨的东西,这里就不多说了。

在Mac中,需要的是一个TrackingArea

当然,和iOS中一样,只有View可以去接收手指的手势等事件。

直接上代码

interface testView()
@property(strong) NSTrackingArea* trackingArea;
@end
@implementation testView

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    
    // Drawing code here.
}

- (void)mouseEntered:(NSEvent *)event{
    [super mouseEntered:event];
    NSLog(@"mouse enter");
}

- (void)mouseExited:(NSEvent *)event{
    [super mouseExited:event];
    NSLog(@"mouse exited");
}

- (void)updateTrackingAreas
{
    if(self.trackingArea != nil) {
        [self removeTrackingArea:self.trackingArea];
    }
    
    int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways);
    self.trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
                                                     options:opts
                                                       owner:self
                                                    userInfo:nil];
    [self addTrackingArea:self.trackingArea];
}

可以定义代理或Block,在mouseEnter和mouseExit的时候监听到鼠标进入和移出视图的事件。

上一篇下一篇

猜你喜欢

热点阅读