[英]Mouse over in a NSView subview
i have a subclass of NSView that handles Mouse events, inside that NSView i have a subview (which is another subclass of NSView).我有一个处理鼠标事件的 NSView 子类,在那个 NSView 里面我有一个子视图(它是 NSView 的另一个子类)。 How can i handle Mouse Events for both NSViews.我如何处理两个 NSView 的鼠标事件。
What i want to achieve is the following:我想要实现的是以下内容:
A NSView where i got a character, when i move my mouse around inside that view the character rotate to follow the mouse.我得到一个角色的 NSView,当我在该视图内移动鼠标时,角色旋转以跟随鼠标。 inside the same there are some Items, when the mouse hover over an item i want to display some information... how can achieve this?里面同样有一些项目,当鼠标悬停在一个项目上时我想显示一些信息......如何实现这一点?
basically: two classes receive and respond to mouse over.基本上:两个类接收和响应鼠标悬停。
Best Regards Kristian最好的问候克里斯蒂安
i guess, you should play with CreateMouse Region and handle Mouse event like mouseenter , mouse exit on it,我想,您应该使用 CreateMouse Region 并处理鼠标事件,例如 mouseenter ,鼠标退出,
refer following method of NSView参考下面的 NSView 方法
addTrackingRect : provide Rect where you would like to capture mouse event for that region you would get following event, addTrackingRect :提供 Rect ,您想在该区域捕获鼠标事件,您将获得以下事件,
mouseDown鼠标按下
mouseUp鼠标向上
mouseEntered鼠标输入
mouseExited鼠标退出
and so on等等
Here is how we did in Swift 5:以下是我们在 Swift 5 中的做法:
class TrackingAreaView: NSView {
private var isMouseOverTheView = false {
didSet {
backgroundColor = isMouseOverTheView ? .red : .green
}
}
private lazy var area = makeTrackingArea()
private var backgroundColor: NSColor? {
didSet {
setNeedsDisplay(bounds)
}
}
init() {
super.init(frame: NSRect()) // Zero frame. Assuming that we are in autolayout environment.
isMouseOverTheView = false
}
required init?(coder: NSCoder) {
fatalError()
}
public override func updateTrackingAreas() {
removeTrackingArea(area)
area = makeTrackingArea()
addTrackingArea(area)
}
public override func mouseEntered(with event: NSEvent) {
isMouseOverTheView = true
}
public override func mouseExited(with event: NSEvent) {
isMouseOverTheView = false
}
private func makeTrackingArea() -> NSTrackingArea {
return NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeInKeyWindow], owner: self, userInfo: nil)
}
open override func draw(_ dirtyRect: NSRect) {
if let backgroundColor = backgroundColor {
backgroundColor.setFill()
dirtyRect.fill()
} else {
super.draw(dirtyRect)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.