我通过在 Xcode 中使用 Storyboard引用自定义 NSView
创建了一个 SpriteKit 场景。但是,我无法使用 SpriteKit 实现任何 mouseMoved
事件,因为我不知道如何引用程序的 NSWindow
以将其 acceptsMouseMovedEvents
属性设置为“true” ".
如何在我的 AppDelegate.swift
文件中创建对我的 NSWindow
的 @IBOutlet
引用,以便我可以更改此属性?
最佳答案
您可以配置一个 NSTrackingArea
对象来跟踪鼠标的移动以及光标何时进入或退出 View 。要创建 NSTrackingArea
对象,您需要指定要跟踪鼠标事件的 View 区域、将接收鼠标事件消息的所有者以及跟踪发生的时间(例如,在关键窗口)。以下是如何将跟踪区域添加到 View 的示例。添加到您的 SKScene
子类,例如 GameScene.swift。
Swift 3 和 4
override func didMove(to view: SKView) {
// Create a tracking area object with self as the owner (i.e., the recipient of mouse-tracking messages
let trackingArea = NSTrackingArea(rect: view.frame, options: [.activeInKeyWindow, .mouseMoved], owner: self, userInfo: nil)
// Add the tracking area to the view
view.addTrackingArea(trackingArea)
}
// This method will be called when the mouse moves in the view
override func mouseMoved(with theEvent: NSEvent) {
let location = theEvent.location(in: self)
print(location)
}
swift 2
override func didMoveToView(view: SKView) {
// Create a tracking area object with self as the owner (i.e., the recipient of mouse-tracking messages
let trackingArea = NSTrackingArea(rect: view.frame, options: NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseMoved, owner: self, userInfo: nil)
// Add the tracking area to the view
view.addTrackingArea(trackingArea)
}
// This method will be called when the mouse moves in the view
override func mouseMoved(theEvent: NSEvent) {
let location = theEvent.locationInNode(self)
println(location)
}
关于swift - 将 acceptMouseMovedEvents 用于带有 Storyboard和 Swift 的 SpriteKit 鼠标操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31306978/