我创建了NSImageView
的子类来捕获mouseEntered
和mouseExited
个事件。
但只会调用mouseUp
和mouseDown
个事件。如何捕获mouseEntered
子类中的mouseExited
和NSImageView
事件?
答案 0 :(得分:75)
如果您想使用mouseEntered:
和mouseExited:
,则需要使用NSTrackingArea
。这是参考NSTrackingArea Class Reference。
示例:强>
//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];
}
答案 1 :(得分:8)
Swift 3 @Justin Boo的答案版本:
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)
}
答案 2 :(得分:6)
Swift 4版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)
}
答案 3 :(得分:2)
Justin Boo的答案的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);
}