Checking Fonts and Colors NSToolbarItem Elements

Using Cocoa with the latest SDK in OSX 10.6.6

I have NSToolbar with custom toolbar elements, as well as built-in fonts and colors for NSToolbarItem elements (NSToolbarShowFontsItem and NSToolbarShowColorsItem identifiers).

I need to be able to enable / disable them in various situations. The validateToolbarItem: task validateToolbarItem: never called for these items (it is called for other toolbar items).

The documentation is not entirely clear:

The toolbar automatically takes on the darkening of an image element when it is clicked and faded when it is turned off. All your code should do confirm element. If the image element has a valid target / action pair, then the toolbar will call NSToolbarItemValidations validateToolbarItem: on the target if the target implements it; otherwise, the item is enabled by default.

I do not explicitly set a goal / action for these two toolbar elements, I want to use their default behavior. Does this mean that I can’t check these items? Or can I do it another way?

Thanks.

+4
source share
1 answer

After some trial and error, I think I was able to figure this out and find a reasonable solution. I will post a quick answer here for future links for others facing the same problem.

This is just another Cocoa design flaw. NSToolbar has hard-coded behavior for setting the target / action for NSToolbarShowFontsItem and NSToolbarShowColorsItem for NSApplication, since documentation hints will never call validateToolbarItem: for these NSToolbarItem elements.

If you need those toolbar elements that have been tested, the trivial task is not to use the default font / color panel elements, but to minimize your own by invoking the same NSApplication actions (see below).

When using the default defaults, you can redirect the target / action to your object, and then call the original actions

 - (void) toolbarWillAddItem:(NSNotification *)notification { NSToolbarItem *addedItem = [[notification userInfo] objectForKey: @"item"]; if([[addedItem itemIdentifier] isEqual: NSToolbarShowFontsItemIdentifier]) { [addedItem setTarget:self]; [addedItem setAction:@selector(toolbarOpenFontPanel:)]; } else if ([[addedItem itemIdentifier] isEqual: NSToolbarShowColorsItemIdentifier]) { [addedItem setTarget:self]; [addedItem setAction:@selector(toolbarOpenColorPanel:)]; } } 

Now validateToolbarItem: will be called::

 - (BOOL)validateToolbarItem:(NSToolbarItem *)theItem { //validate item here } 

And here are the actions that will be called:

 -(IBAction)toolbarOpenFontPanel:(id)sender { [NSApp orderFrontFontPanel:sender]; } -(IBAction)toolbarOpenColorPanel:(id)sender { [NSApp orderFrontColorPanel:sender]; } 

I think that the engineers who designed it never thought that it would be necessary to check the elements of the font / color panel. Hover over your mouse.

+1
source

Source: https://habr.com/ru/post/1339086/


All Articles