mouseEntered and mouseExited not called in NSImageView SubClass

走远了吗. 提交于 2019-12-30 01:36:12

问题


I created a subclass of NSImageView to capture mouseEntered and mouseExited events. But only mouseUp and mouseDown events are getting called. How to capture the mouseEntered and mouseExited events in NSImageView subclass?


回答1:


If You want to use mouseEntered: and mouseExited: You need to use NSTrackingArea. Here is reference NSTrackingArea Class Reference.

Example:

//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];
}



回答2:


Swift 3 Version of @Justin Boo's answer:

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)
}



回答3:


Swift 4 version of Justin Boo's answer

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)
}



回答4:


C# Xamarin version of Justin Boo's answer

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);
}


来源:https://stackoverflow.com/questions/11188034/mouseentered-and-mouseexited-not-called-in-nsimageview-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!