在讨论苹果环境下的开发,不可避免会引用到官方文档:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Toolbars/Toolbars.html
这里讨论的是使用代码来创建工具栏:
- (void)layoutToolbar
{
NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"SimpleToolbar"];
[toolbar setAllowsUserCustomization:NO];
[toolbar setAutosavesConfiguration:NO];
[toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
[toolbar setSizeMode:NSToolbarSizeModeSmall];
[toolbar setDelegate:self];
[self.window setToolbar:toolbar];
[toolbar release], toolbar = nil;
}
在为toolbar设置了代理对象后,代理对象需要提供一些信息:
1. 默认使用哪些标识符;
2. 允许使用哪些标识符;
3. 为每个标识符提供对应的item。
#pragma mark - NSToolbarDelegate
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
return @[SimpleToolbarItemIdentifier];
}
- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
{
return @[SimpleToolbarItemIdentifier];
}
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier] autorelease];
if ([itemIdentifier isEqualToString:SimpleToolbarItemIdentifier]) {
[toolbarItem setLabel:@"Add"];
[toolbarItem setPaletteLabel:@"Add"];
[toolbarItem setToolTip:@"Add"];
[toolbarItem setImage:[NSImage imageNamed:@"addIcon"]];
[toolbarItem setMinSize:CGSizeMake(25, 25)];
[toolbarItem setMaxSize:CGSizeMake(100, 100)];
[toolbarItem setTarget:self];
[toolbarItem setAction:@selector(simpleToolbarItemDidClick:)];
} else {
toolbarItem = nil;
}
return toolbarItem;
}
这样简单的代码就基本够用了。