iOS - 工具栏

2025-10-03 00:08:53

❮ 上一节

下一节 ❯

iOS - 工具栏

工具栏的使用

如果我们想根据当前视图操作某些东西,我们可以使用工具栏。

示例是带有收件箱项目的电子邮件应用程序,该项目具有删除、收藏、回复等选项。 如下图所示。

重要属性

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 并为 UILabel 创建一个 IBoutlet 并将其命名为 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.

}

输出

当我们运行应用程序时,我们会得到以下输出 −

单击 tool1 和 tool2 栏按钮,我们得到以下信息 −

❮ iOS - UI 元素