8

I tried to change the default cursor in my cocoa application. I read about this but the standard approach isn't working for me.

I try to add to my OpenGLView subclass this method:

- (void) resetCursorRects
{
    [super resetCursorRects];
    NSCursor * myCur = [[NSCursor alloc] initWithImage:[NSImage imageNamed:@"1.png"] hotSpot:NSMakePoint(8,0)];
    [self addCursorRect: [self bounds]
          cursor: myCur];
    NSLog(@"Reset cursor rect!");

} 

It`s not working. Why?

Daniyar
  • 2,975
  • 2
  • 26
  • 39
sch_vitaliy
  • 91
  • 1
  • 2

2 Answers2

16

There're two ways you can do it. First - the most simple - is to change the cursor while the mouse enters the view and leaves it.

- (void)mouseEntered:(NSEvent *)event
  {
   [super mouseEntered:event];
   [[NSCursor pointingHandCursor] set];
  }

- (void)mouseExited:(NSEvent *)event
  {
   [super mouseExited:event];
   [[NSCursor arrowCursor] set];
  }

Another way is to create tracking area (i.e. in awakeFromNib-method), and override - (void)cursorUpdate:-method

- (void)createTrackingArea
  {
   NSTrackingAreaOptions options = NSTrackingInVisibleRect | NSTrackingCursorUpdate;
   NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:self.bounds options:options owner:self userInfo:nil];
   [self addTrackingArea:area];
  }


- (void)cursorUpdate:(NSEvent *)event
  {
   [[NSCursor pointingHandCursor] set];
  }
Daniyar
  • 2,975
  • 2
  • 26
  • 39
  • 5
    for using the NSCursor.set, you must not allow other components to change the cursor while it is in your view. To do this, you can disable cursor rects for the window on Mouse enter and re-enable them on mouse exit. If you don't do this, your cursor might be reset to Arrow after a few seconds. – Radu Simionescu Dec 05 '15 at 01:22
5

For those of you looking for a Swift solution, the syntax is:

override func mouseEntered(with event: NSEvent) {
    super.mouseEntered(with: event)

    NSCursor.pointingHand.set()
}
koen
  • 5,383
  • 7
  • 50
  • 89