我创建了一个子类NSImageView
来捕获mouseEntered
和mouseExited
事件。但只有mouseUp
和mouseDown
事件被调用。如何捕获子类中的mouseEntered
和mouseExited
事件NSImageView
?
问问题
12116 次
4 回答
84
如果您想使用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];
}
于 2012-06-25T13:57:59.553 回答
11
Swift 4 版本的Justin Boo 的回答
override func updateTrackingAreas() {
super.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)
}
于 2018-06-03T01:25:03.277 回答
10
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)
}
于 2017-07-14T11:47:18.630 回答
4
C# Xamarin 版本的 Justin Boo 的回答
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);
}
于 2018-07-12T16:01:15.587 回答