在 IOS 中如果我們想操縱一些東西,基于目前的視圖,我們可以使用工具欄(toolbar)。
例如將電子郵件應(yīng)用程序的收件箱項(xiàng)選擇刪除,做標(biāo)志,回復(fù)等。如下所示。
重要的屬性
barStyle
items
-(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]; }
為了解所執(zhí)行的操作,我們添加 UILabel 在 ViewController.xib 中并創(chuàng)建一個(gè) IBOutlet 的 UILabel,并將它命名為 label。
我們還需要添加兩個(gè)方法以執(zhí)行工具欄項(xiàng)目的操作,如下圖所示
-(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. }
現(xiàn)在,當(dāng)我們運(yùn)行程序時(shí),我們會(huì)得到下面的輸出。
點(diǎn)擊 tool1 和 tool2 欄按鈕,我們得到