Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa nsview change cursor

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?

like image 851
sch_vitaliy Avatar asked Apr 28 '15 06:04

sch_vitaliy


2 Answers

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];
  }
like image 50
Daniyar Avatar answered Dec 01 '22 09:12

Daniyar


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()
}
like image 23
koen Avatar answered Dec 01 '22 11:12

koen