问题
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