Set the cursor to a pointing hand over a text view
Asked Answered
Z

2

5

Is there a way to set the cursor to a pointing hand over a text view without subclassing NSTextView?

I read a lot about NSTrackingAreas, tested a lot of examples, set different tracking options and implemented different methods, but the cursor still remains an I-Beam. I have read that it is an AppKit automatic feature, so how can I prevent this?

Thank you!

Zonazonal answered 1/12, 2012 at 10:17 Comment(2)
You could/should do this with NSCursor. Check this [comment][1]. [1]: #5545257Valentine
An updated answer for Swift: https://mcmap.net/q/1511524/-changing-nscursor-for-nsview-above-an-nstextviewFactitive
Z
4

I had to subclass. After a couple of hours to test a lot of methods and options, this finally worked :

@implementation ATTextView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _trackingArea = [[NSTrackingArea alloc]initWithRect:[self bounds] options: (NSTrackingMouseMoved | NSTrackingActiveInKeyWindow) owner:self userInfo:nil];
        [self addTrackingArea:_trackingArea];
    }
    return self;
}

- (void)mouseMoved:(NSEvent *)event
{
    if ([self isEditable]) [[NSCursor IBeamCursor] set];
    else [[NSCursor pointingHandCursor] set];
}

- (void)updateTrackingAreas {
    [super updateTrackingAreas];
    [self removeTrackingArea:_trackingArea];
    _trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options: (NSTrackingMouseMoved | NSTrackingActiveInKeyWindow) owner:self userInfo:nil];
    [self addTrackingArea:_trackingArea];
}
@end

Just to find the correct example (Cocoa is 80% doc reading and 20% coding): https://developer.apple.com/library/mac … 0i-CH8-SW1

Zonazonal answered 3/12, 2012 at 19:31 Comment(0)
K
3

this worked for me using Swift 3:

class HyperlinkTextField : NSTextField {

    override func resetCursorRects() {
        discardCursorRects()
        addCursorRect(self.bounds, cursor: NSCursor.pointingHand())
    }

}
Kiowa answered 8/1, 2017 at 18:27 Comment(2)
What does the discardCursorRects do?Cosimo
Will this work with NSTextView, which is what the question is about?Bollen

© 2022 - 2024 — McMap. All rights reserved.