Automatic Styling/Tinting of NSToolbarItem

2020-07-22 09:40发布

问题:

Is there a way to tell OS X to automatically style/tint a NSToolbarItem?

I've added an "Image Toolbar Item" via IB/Xcode and set the icon to a black PDF as described in the documentation.

However, my result does not resemble that of, for instance, the App Store:

I'm looking for something akin to what the TabBar in iOS does by default.

I'm new to OS X development... So any guidance would be appriciated!

回答1:

Images need to be made template'd in order to get the correct styling (such as the engraved & blue styling).

This can be done in code with -[NSImage setTemplate:] or by having your image names end with "Template" (requiring no code changes).


To get the blue styling specifically, you have to set a borderless NSButton as the custom view of the toolbar item (rather than it being a standard item). That button has to have a type that results in it showing its state (e.g. a Round-Textured Toggle button), and when it has an On state, it will get then blue styling.



回答2:

If you're trying to create a tinted toolbar item in code, This is how I did it. Create the correct type of button NSButtonTypeToggle then set the buttons properties, then add the button to the toolbar item's custom view and finally the toolbar item is returned.

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSToolbarItemIdentifier)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag {

    // create toolbar items
    NSToolbarItem *toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
    toolbarItem.label = @"title";
    NSImage *iconImage = [NSImage imageNamed:NSImageNameColumnViewTemplate];
    NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 40.0, 40.0)];
    button.title = @"";
    button.image = iconImage;
    [button setButtonType:NSButtonTypeToggle];
    button.bezelStyle = NSBezelStyleTexturedRounded;
    button.action = @selector(toggleColumnView:);
    [toolbarItem setView:button];
    return toolbarItem; 
}