I want to use a custom cursor for my project. Now, using one of the system cursors in XCode is no biggie, i simply call:
NSCursor.crosshair() .set()
(just an example)
This works fine but then I try to set my custom cursor the following way: (inside didMove: to View or inside sceneDidLoad(), it doesn't seem to matter which.)
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)
When I try to build I get an error in line 3 saying "unexpectedly found nil".
So then I changed the code to this:
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)
Now the project builds, but nothing happens. The cursor doesn't change.
I also tried these lines here:
NSCursor.init(image: image!, hotSpot: spot)
NSCursor.set(customCursor)()
Again, the project builds but the cursor doesn't change. What am I doing wrong here?
I tried to follow all the guidelines i could find but the Apple Documentation on cursor events is not much help since its heavily outdated and mouse related topics are generally very rare since most stuff is about ios. Thanks in advance for your help.
From the
NSImage(byReferencingFile:)docs,As a result, the image is not loaded from the file when the
addCursorRect()method is called. In fact, the image size is (height:0, width:0) as shown in the following.I suggest you use
NSImage(named:)to create the image from a file:Also,
addCursorRect(image:,hotSpot:)should only be called from theresetCursorRects()method. From the docs,addCursorRect()is an instance method ofNSViewand, for SpriteKit, the view is anSKViewwhich inherits fromNSView. Accordingly, you could subclass SKView, override the subclass'saddCursorRect()method, and change the view's class (to our SKView subclass) in the Storyboard.Alternatively, you can accomplish this by extending SKView and overriding the
resetCursorRects()method. For example,For Xcode 9.3
For Xcode 9.2
For older Xcode versions:
Project Navigator with cursor image highlighted.