使用宏分别定义文本条目,图像条目,系统条目和定制视图条目,这些宏都提供一个可置入UIToolBar 的自动发布UIBarButtonItem。
#define COOKBOOK_PURPLE_COLOR [UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
#define BARBUTTON(TITLE, SELECTOR) [[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease]
#define IMGBARBUTTON(IMAGE, SELECTOR) [[[UIBarButtonItem alloc] initWithImage:IMAGE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease]
#define SYSBARBUTTON(ITEM, SELECTOR) [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:ITEM target:self action:SELECTOR] autorelease]
#define CUSTOMBARBUTTON(VIEW) [[[UIBarButtonItem alloc] initWithCustomView:VIEW] autorelease]
//创建工具栏
UIToolbar *tb = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
tb.center = CGPointMake(160.0f, 200.0f);
NSMutableArray *tbitems = [NSMutableArray array];
[tbitems addObject:BARBUTTON(@"Title", @selector(action))];
[tbitems addObject:SYSBARBUTTON(UIBarButtonSystemItemAdd, @selector(action))];
[tbitems addObject:IMGBARBUTTON([UIImage imageNamed:@"TBUmbrella.png"], @selector(action))];
[tbitems addObject:CUSTOMBARBUTTON([[[UISwitch alloc] init] autorelease])];
[tbitems addObject:SYSBARBUTTON(UIBarButtonSystemItemFlexibleSpace, nil)];
[tbitems addObject:IMGBARBUTTON([UIImage imageNamed:@"TBPuzzle.png"], @selector(action))];
// Add fixed 20 pixel width
UIBarButtonItem *bbi = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil] autorelease];
bbi.width = 20.0f;
[tbitems addObject:bbi];
tb.items = tbitems;
[self.view addSubview:tb];
[tb release];
工具栏提示:
处理工具栏是,使用一些小技巧可能会很有用。
1、固定空间可以拥有宽度----在所有UIBarButtonITem中,只有 UIBarBuutonSystemItemFixedSpace 条目可以被分配一个宽度,因此,创建空间条目、设置其宽度,然后在将其添加到条目列中。
2、使用一个灵活空间进行左对齐或右对齐----在条目列表中开始添加一个 UIBarButtonSystemITemFlexibleSpace 会使所有剩余条目右对齐。在末尾添加一个,则左对齐。使用两个 UIBarButtonSystemItemFlexibleSpace ,一个添加在开头,一个添加在末尾,会使剩余条目居中对齐。
3、考虑遗漏的条目----根据上下文隐藏栏按钮条目时,不要只使用灵活的空间分配来除去条目。而应使用一个与条目原来大小匹配的固定宽度的空间代替该条目。这样做会在条目消失前后保存布局并保持其他所有图标位置不变。