swift - 将 acceptMouseMovedEvents 用于带有 Storyboard和 Swift 的 SpriteKit 鼠标操作

标签 swift cocoa sprite-kit iboutlet xcode-storyboard

我通过在 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/

相关文章:

cocoa - 唯一标识 ABRecord 记录 : Is [ABRecord uniqueId] immutable?

ios - 如何修复此共享按钮?

swift - 我怎样才能改变我的程序,让这个对象只对一次触摸使用react?

swift - UIScrollView 中的 UIStackView 中的点击检测 UIImageView

ios - 移至下一个响应者时键盘闪烁

cocoa - 我非常感谢新 Cocoa 程序员的帮助

objective-c - 将可点击的 URL 添加到我的 Cocoa View - 我做错了吗?

ios - 如何在 Swift 和 Sprite Kit 中创建暂停和取消暂停按钮?

ios - 在 ViewController 中的属性闭包中定义 UIBarButtonItems

ios - Spritekit (Swift) 是否允许使用两个不同的相机节点?