ToolBar Demo

工具栏是个很常见的组件。我们来看看它的常用功能和设置吧。

先建立了一个ToolBarDemo的工程,模板就选singleView。


1.我们从对象库里找到这四个相关的组件:

[转载]Xcode <wbr>iOS <wbr>工具栏ToolBar演示

ToolBar、Bar Button Item、Fixed Space Bar Button Item、Flexible Space Bar Button Item。前两个是可见的工具栏和工具栏项目,后两个只是用于调节按钮位置固定调节和灵活调节。

先拖动ToolBar到视图底部,当然你也可以放到顶部或任意位置。

[转载]Xcode <wbr>iOS <wbr>工具栏ToolBar演示

添加一些组件来看看。

要说明的是,Fixed Space Bar Button Item是固定的(也可调)间距,而Flexible Space Bar Button Item则会自动调整现有按钮使最大限度占据工具栏的所有空间。

[转载]Xcode <wbr>iOS <wbr>工具栏ToolBar演示

2.按钮Bar Button Item有三种Style:Plain(可使用自定义图片),Boarded和Done。其他属性则望文生义即可。要使按钮不可用,更改Enable属性即可。而Tool Bar也可以做一些调整(主要也是调整style)。

3.如何捕捉按钮的动作呢?

我们做一些补充:先给第一个按钮style设置成plain,然后设定一张image(24x24),另还需准备一张不同的图片用于演示点击后按钮改变的图片,再添加一个Label到视图来显示结果,最后把其他按钮的title做些更改以区分。

[转载]Xcode <wbr>iOS <wbr>工具栏ToolBar演示

4.编写代码

// ToolBarDemoViewController.h
#import <UIKit/UIKit.h>
@interface ToolBarDemoViewController : UIViewController{
   UIBarButtonItem
   UIBarButtonItem
   UIBarButtonItem
   UIBarButtonItem
   UILabel
}
@property (strong, nonatomic) IBOutlet UIBarButtonItem
@property (strong, nonatomic) IBOutlet UIBarButtonItem
@property (strong, nonatomic) IBOutlet UILabel
-(IBAction)btPress:(id)sender;
@end
// ToolBarDemoViewController.m
#import "ToolBarDemoViewController.h"
@implementationToolBarDemoViewController
@synthesize bt1;
@synthesize bt4;
@synthesize output;
-(IBAction)btPress:(id)sender{
   UIBarButtonItem
   if (barButtonItem.title ==NULL){
       if (bt1.image == [UIImage imageNamed:@"singleicon.png"] ) {
           bt1.image = [UIImage imageNamed:@"toolicon.png"];
      
       else
           bt1.image = [UIImage imageNamed:@"singleicon.png"];
  
   output.text = [[NSString alloc] initWithFormat:@"%@ Pressed!",barButtonItem.title];
}

需要注意的是,Plain类型的按钮是没有title的,即为Null。

5.运行结果如下

[转载]Xcode <wbr>iOS <wbr>工具栏ToolBar演示

 

[转载]Xcode <wbr>iOS <wbr>工具栏ToolBar演示