iOS - 工具欄



工具欄使用

如果我們希望基於當前檢視對某些內容進行操作,則可以使用工具欄。

示例是帶有一個收件箱專案,帶有刪除、收藏、回覆等選項的電子郵件應用程式。如下所示。

iOS Tutorial

重要屬性

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

輸出

當我們執行應用程式時,我們將獲得以下輸出 −

iOS Tutorial

單擊 tool1 和 tool2 欄按鈕,我們將獲得以下內容 −

iOS Tutorial
ios_ui_elements.htm
廣告
© . All rights reserved.