4

I want to display tooltips over parts of an attributed string, and thought that using an NSToolTipAttributeName attribute on the required ranges would do the trick but I can't get it to work. I am trying in MACOS, Xcode (9.2)

NSString *fullString = @"Create a new tooltip";

NSString *compareString =@"tooltip";

NSRange tooltipRange = [fullString rangeOfString: compareString]; 

[senderTextView.textStorage addAttribute:NSToolTipAttributeName
                        value:@"Custom tooltip"
                        range:tooltipRange];

[senderTextView.textStorage addAttribute:NSForegroundColorAttributeName
     value:[NSColor redColor] range:tooltipRange];

The word "tooltip" is shown in red as expected, but no tooltip appears when I hover over it. What am I missing?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nomita
  • 51
  • 4

1 Answers1

0

Couple of ways to do this, using the NSToolTipAttributeName in combination with NSLinkAttributeName, e.g.:

NSMutableDictionary* labelAttributes = [NSMutableDictionary new];
labelAttributes[NSToolTipAttributeName] = @"Tooltip";
labelAttributes[NSLinkAttributeName] = @"Link";
NSAttributedString* labelString = [NSAttributedString
    attributedString:@"Display"]
    withAttributes:labelAttributes];

Being careful not to forget displaysLinkToolTips = YES on the NSTextView.

Alternately, you can use the NSView Tooltips API, which provides:

- (NSToolTipTag)addToolTipRect:(NSRect)rect owner:(id)owner userData:(void *)data;
alfwatt
  • 2,010
  • 2
  • 18
  • 29
  • This is wrong, there's no need for a link attribute (and no need for `displaysLinkToolTips`). Tooltips can be presented on their own. – yonilevy Aug 27 '19 at 17:34