0

I have a class CustomToolbarItem which inherits from NSToolbarItem. From within the CustomToolbarItem class itself, during initialisation, can I get a reference to the NSWindow instance to which it is added?

I have tried adding the following code to AwakeFromNib but the view is null.

var window = View.Window;
fractor
  • 1,534
  • 2
  • 15
  • 30
  • I'm curious how you got to the point of creating a toolbar item *without* a reference to a window at hand. Toolbars only relate to windows, and while I suppose you could create one programmatically outside of a window context, I can't quite see the advantage in doing so. Maybe there's a solution to the problem hiding in that. – Ted Wrigley Aug 29 '19 at 15:02
  • I do have a window reference to hand and indeed my current solution is to have a Window property on the toolbar subclass which I set from outside. Just would be a bit neater if the toolbar class could do it itself. If it can't be done, then I can live with it. – fractor Aug 29 '19 at 15:41
  • I'll grant that is a little odd. If you really want a solution, you could always subclass NSToolbar and add a `window` property. – Ted Wrigley Aug 29 '19 at 15:51
  • Sorry, I meant a Window property on the *NSToolbarItem* subclass. – fractor Aug 29 '19 at 16:10
  • Well yes, I know, but a window property would *naturally* go on the toolbar, not the toolbar item, and we'd reach for it with `myToolBarItem.toolbar.window`. I mean, I suppose you could subclass NSToolbarItem and add a window property, but... Meh, that feels whack to me. Sorry, a bit of ObjC OCD... – Ted Wrigley Aug 29 '19 at 16:26
  • Thing is, I want to observe `effectiveAppearance` on the window so that my toolbar item can manage its own appearance accordingly. Creating a Window property on a toolbar subclass does have the benefit of only needing to set the property once on the toolbar, not for every item, but then my toolbar item subclass needs to know that its toolbar is of a type that has such a Window property rather than plain old NSToolbar, which means casting. – fractor Aug 30 '19 at 07:35

1 Answers1

0

An NSToolbarItem has an associated view, and a view has an associated window, so something like:

myCustomToolbarItem.view.window

should get you what you want.

CRD
  • 52,522
  • 5
  • 70
  • 86
  • Thank you. I need to access the window from within the NSToolbarItem subclass itself during initialisation. The initialisation part wasn't mentioned in the original question so I've updated it. – fractor Aug 29 '19 at 10:34