和的mouseEntered中的mouseExited NSImageView子类不叫(mouseE

2019-06-25 17:46发布

我创建的子类NSImageView捕捉mouseEnteredmouseExited事件。 但是,只有mouseUpmouseDown事件获取调用。 如何捕获mouseEnteredmouseExited在事件NSImageView子?

Answer 1:

如果您想使用mouseEntered:mouseExited:您需要使用NSTrackingArea 。 下面是参考NSTrackingArea类参考 。

例:

//Add this to Your imageView subclass

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

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

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

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


Answer 2:

斯威夫特3版本的@Justin嘘的回答:

private var trackingArea: NSTrackingArea?

override func updateTrackingAreas() {
    super.updateTrackingAreas()

    if let trackingArea = self.trackingArea {
        self.removeTrackingArea(trackingArea)
    }

    let options: NSTrackingAreaOptions = [.mouseEnteredAndExited, .activeAlways]
    let trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil)
    self.addTrackingArea(trackingArea)
}


Answer 3:

斯威夫特4版的贾斯汀嘘的答案

override func updateTrackingAreas() {
    for trackingArea in self.trackingAreas {
        self.removeTrackingArea(trackingArea)
    }

    let options: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeAlways]
    let trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil)
    self.addTrackingArea(trackingArea)
}


Answer 4:

贾斯汀嘘的答案C#Xamarin版本

public override void UpdateTrackingAreas ()
{
    base.UpdateTrackingAreas ();

    foreach (var item in TrackingAreas ()) {
        RemoveTrackingArea (item);
    }

    var options = NSTrackingAreaOptions.MouseEnteredAndExited | NSTrackingAreaOptions.ActiveAlways;

    var trackingArea = new NSTrackingArea (this.Bounds, options, this, null);

    AddTrackingArea (trackingArea);
}


文章来源: mouseEntered and mouseExited not called in NSImageView SubClass