iOS工具栏

工具栏的使用

我们可以使用工具栏修改视图元素。

如,邮件应用程序里的收件箱栏中有删除、分享、答复等等。如下所示:

toolbar

重要的属性

  • barStyle
  • items

添加自定义方法 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];
}

为了解所执行的操作我们在我们的ViewController.xib中添加UILabel Iboutlet并为 UILabel 创建命名为标签的IBoutlet。

我们还需要添加两个方法来执行,如下所示的工具栏项的操作:

-(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.
}

输出

现在当我们运行该应用程序我们会看到下面的输出。

toolbarOutput

单击我们得到的 tool1 和 tool2 栏按钮

toolbarActionOutput

其他扩展