1

我想为我的项目使用自定义光标。现在,在 XCode 中使用其中一个系统游标并不重要,我只需调用:

NSCursor.crosshair() .set() 

(只是一个例子)

这工作正常,但后来我尝试通过以下方式设置我的自定义光标:(在 didMove: 内查看或在 sceneDidLoad() 内,这似乎无关紧要。)

let image = NSImage(named: "hand1.png")
let spot = NSPoint(x: 4, y: 8)
let customCursor = NSCursor(image: image!, hotSpot: spot)
self.view!.addCursorRect(self.frame, cursor:customCursor)

当我尝试构建时,我在第 3 行得到一个错误,说“意外发现 nil”。

所以我把代码改成这样:

let image = NSImage(byReferencingFile: "hand1.png")
let spot = NSPoint(x: 4, y: 8)
let customCursor = NSCursor(image: image!, hotSpot: spot)
self.view!.addCursorRect(self.frame, cursor: customCursor)

现在项目构建,但没有任何反应。光标不变。

我也在这里尝试了这些行:

NSCursor.init(image: image!, hotSpot: spot)
NSCursor.set(customCursor)()

同样,项目构建,但光标没有改变。我在这里做错了什么?

我试图遵循我能找到的所有指导方针,但关于光标事件的 Apple 文档并没有多大帮助,因为它严重过时且与鼠标相关的主题通常非常罕见,因为大多数东西都是关于 ios 的。在此先感谢您的帮助。

4

1 回答 1

1

NSImage(byReferencingFile:)文档中,

该方法懒惰地初始化图像对象。在应用程序尝试绘制图像或请求有关它的信息之前,它实际上不会打开指定的文件或从其数据创建任何图像表示。

因此,addCursorRect()调用该方法时不会从文件中加载图像。实际上,图像大小为(height:0,width:0)如下图所示。

if let image = NSImage(byReferencingFile:"cursorImage.png") {
    print("\(image.size)")
}

// (0.0, 0.0)

我建议您使用NSImage(named:)从文件创建图像:

if let image = NSImage(named:NSImage.Name("cursorImage.png")) {
    print("\(image.size)")
}

// (32.0, 32.0)

此外,addCursorRect(image:,hotSpot:)应该只从resetCursorRects()方法中调用。从文档中,

此方法旨在仅由 resetCursorRects() 方法调用。如果以任何其他方式调用,生成的光标矩形将在下次重建视图的光标矩形时被丢弃。

addCursorRect()是一个实例方法NSView,对于 SpriteKit,视图是一个SKView继承自NSView. 因此,您可以继承 SKView,覆盖子类的addCursorRect()方法,并在 Storyboard 中更改视图的类(到我们的 SKView 子类)。

或者,您可以通过扩展 SKView 并覆盖该resetCursorRects()方法来完成此操作。例如,

对于 Xcode 9.3

extension SKView {
    override open func resetCursorRects() {
        if let image = NSImage(named:NSImage.Name(rawValue:"cursorImage.png")) {
            let spot = NSPoint(x: 0, y: 0)
            let customCursor = NSCursor(image: image, hotSpot: spot)
            addCursorRect(visibleRect, cursor:customCursor)
        }
    }
}

对于 Xcode 9.2

extension SKView {
    override open func resetCursorRects() {
        if let image = NSImage(named:NSImage.Name("cursorImage.png")) {
            let spot = NSPoint(x: 0, y: 0)
            let customCursor = NSCursor(image: image, hotSpot: spot)
            addCursorRect(visibleRect, cursor:customCursor)
        }
    }
}

对于较旧的 Xcode 版本:

extension SKView {
    override open func resetCursorRects() {
        if let path = Bundle.main.path(forResource: "cursorImage", ofType: "png") {
            if let image = NSImage(contentsOfFile:path) {
                let spot = NSPoint(x: 0, y: 0)
                let customCursor = NSCursor(image: image, hotSpot: spot)
                addCursorRect(visibleRect, cursor:customCursor)
            }
        }
    }
}

突出显示光标图像的项目导航器。

在此处输入图像描述

于 2018-05-06T19:45:34.233 回答