关于NSToolbar的使用

来源:互联网 发布:ce6800 开启端口自协商 编辑:程序博客网 时间:2024/05/16 08:57

在讨论苹果环境下的开发,不可避免会引用到官方文档:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Toolbars/Toolbars.html

这里讨论的是使用代码来创建工具栏:

[cpp] view plaincopy
  1. - (void)layoutToolbar  
  2. {  
  3.     NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"SimpleToolbar"];  
  4.       
  5.     [toolbar setAllowsUserCustomization:NO];  
  6.     [toolbar setAutosavesConfiguration:NO];  
  7.     [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];  
  8.     [toolbar setSizeMode:NSToolbarSizeModeSmall];  
  9.       
  10.     [toolbar setDelegate:self];  
  11.       
  12.     [self.window setToolbar:toolbar];  
  13.       
  14.     [toolbar release], toolbar = nil;  
  15. }  

在为toolbar设置了代理对象后,代理对象需要提供一些信息:

1. 默认使用哪些标识符;

2. 允许使用哪些标识符;

3. 为每个标识符提供对应的item。

[cpp] view plaincopy
  1. #pragma mark - NSToolbarDelegate  
  2.   
  3. - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar  
  4. {  
  5.     return @[SimpleToolbarItemIdentifier];  
  6. }  
  7.   
  8. - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar  
  9. {  
  10.     return @[SimpleToolbarItemIdentifier];  
  11. }  
  12.   
  13. - (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag  
  14. {  
  15.     NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier] autorelease];  
  16.       
  17.     if ([itemIdentifier isEqualToString:SimpleToolbarItemIdentifier]) {  
  18.         [toolbarItem setLabel:@"Add"];  
  19.         [toolbarItem setPaletteLabel:@"Add"];  
  20.         [toolbarItem setToolTip:@"Add"];  
  21.         [toolbarItem setImage:[NSImage imageNamed:@"addIcon"]];  
  22.           
  23.         [toolbarItem setMinSize:CGSizeMake(25, 25)];  
  24.         [toolbarItem setMaxSize:CGSizeMake(100, 100)];  
  25.           
  26.         [toolbarItem setTarget:self];  
  27.         [toolbarItem setAction:@selector(simpleToolbarItemDidClick:)];  
  28.     } else {  
  29.         toolbarItem = nil;  
  30.     }  
  31.       
  32.     return toolbarItem;  
  33. }  

这样简单的代码就基本够用了。
0 0
原创粉丝点击