添加自定义方法 addToolbar
-(void)addToolbar {
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
UIBarButtonItem *customItem1 = [[UIBarButtonItem alloc]
initWithTitle:@"Tool1" style:UIBarButtonItemStyleBordered
target:self action:@selector(toolBarItem1:)];
UIBarButtonItem *customItem2 = [[UIBarButtonItem alloc]
initWithTitle:@"Tool2" style:UIBarButtonItemStyleDone
target:self action:@selector(toolBarItem2:)];
NSArray *toolbarItems = [NSArray arrayWithObjects:
customItem1,spaceItem, customItem2, nil];
UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:
CGRectMake(0, 366+54, 320, 50)];
[toolbar setBarStyle:UIBarStyleBlackOpaque];
[self.view addSubview:toolbar];
[toolbar setItems:toolbarItems];
}
为了了解所执行的操作,我们添加了一个 UILabel 在我们的 ViewController.xib 并创建一个 IBoutlet 对于 UILabel 并将其命名为 label.
我们还需要添加两个方法来执行工具栏项目的操作,如下所示。
-(IBAction)toolBarItem1:(id)sender {
[label setText:@"Tool 1 Selected"];
}
-(IBAction)toolBarItem2:(id)sender {
[label setText:@"Tool 2 Selected"];
}
更新 ViewController.m 中的 viewDidLoad 如下 -
- (void)viewDidLoad {
[super viewDidLoad];
// The method hideStatusbar called after 2 seconds
[self addToolbar];
// Do any additional setup after loading the view, typically from a nib.
}