Add a tooltip rectangle to NSToolBarItem's default view

37 Views Asked by At

I have some NSToolBarItems to allow undo/redo in my app. I want them to show the name of undo/redo actions in their tooltip.

I can specify the tooltip of an NSToolBarItem vial its toolTip property. But I'm not sure when this property should be set. I haven't found a way to be notified when the undo manager has recorded a new action to undo or redo.

It would be better to dynamically return the tooltip string when the user hovers the toolbar item. But this requires adding a tooltip rectangle to a view that I cannot access. Indeed, the view property of NSToolBarItem returns nil by default. It does not return nil if I set the view property with my own view, but a NSToolBarItem uses a private subclass of NSButton as view, by default. This subclass implements nice behaviours that NSButton doesn't. So I'd rather use the default view.

Is there a way to add a tooltip rectangle to an NSToolBarItem's view that doesn't use a custom view? IOW, how can I access this view?

1

There are 1 best solutions below

3
HangarRash On

You don't need to hack NSToolbarItem. Use the NSUndoManagerCheckpointNotification notification on your undo manager. Every time it is called you can update the tooltip of the two toolbar bar items.

[NSNotificationCenter.defaultCenter addObserverForName:NSUndoManagerCheckpointNotification object:self.undoManager queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
    NSString *undoTitle = self.undoManager.undoMenuItemTitle;
    NSString *redoTitle = self.undoManager.redoMenuItemTitle;
    // Update the toolbar items' tooltips
}];

You can also access the relevant undo manager via note.object in the block.