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?

2 Answers 2

17

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];
  }
1
  • 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. Dec 5, 2015 at 1: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()
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.