创建一个导航按钮,须要做一下工作:
创建一个 UIBarButtonItem 类实例。
使用视图控件的NavigationItem 属性给导航栏添加按钮。NavigationItem 属性允许我们设置这个导航栏。这个属性自身有两个属性,分别为 rightBarButtonItem 和 leftBarButtonItem。这两个属性都属于 UIBarButtonItem 类。
下面是一个为导航栏右侧添加按钮的例子:
- (void)performAdd:(id)paramSender{
NSLog(@"Action method got called.");
}
-(void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First Controller";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Add" style:UIBarButtonItemStylePlain
target:self
action:@selector(performAdd:)];
}
结果如下:
这里面style的参数是UIBarButtonSystemItem枚举类型中的任意一个,如下所示:
typedef enum {
UIBarButtonSystemItemDone,
UIBarButtonSystemItemCancel,
UIBarButtonSystemItemEdit,
UIBarButtonSystemItemSave,
UIBarButtonSystemItemAdd,
UIBarButtonSystemItemFlexibleSpace,
UIBarButtonSystemItemFixedSpace,
UIBarButtonSystemItemCompose,
UIBarButtonSystemItemReply,
UIBarButtonSystemItemAction,UIBarButtonSystemItemOrganize,
UIBarButtonSystemItemBookmarks,UIBarButtonSystemItemSearch,
UIBarButtonSystemItemRefresh,UIBarButtonSystemItemStop,
UIBarButtonSystemItemCamera,UIBarButtonSystemItemTrash,
UIBarButtonSystemItemPlay,UIBarButtonSystemItemPause,
UIBarButtonSystemItemRewind,
UIBarButtonSystemItemFastForward,
UIBarButtonSystemItemUndo,
UIBarButtonSystemItemRedo,
UIBarButtonSystemItemPageCurl,
} UIBarButtonSystemItem;
类 UIBarButtonItem 中的真正最大的初始化方法中,其中一个是 initWithCustomView:方法.这里接收的参数是任何视图类.
下面举个例子:
- (void) switchIsChanged:(UISwitch *)paramSender{
if ([paramSender isOn]){ NSLog(@"Switch ison."); }
else {NSLog(@"Switch is off."); }
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First Controller";
UISwitch *simpleSwitch = [[UISwitch alloc] init];
simpleSwitch.on = YES;
[simpleSwitch addTarget:selfaction:@selector(switchIsChanged:)forControlEvents:UIControlEventValueChanged];self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:simpleSwitch];
}
运行结果如下:
ok,最后我们做个稍微复杂一点的:
- (void) segmentedControlTapped:(UISegmentedControl *)paramSender{ if ([paramSender selectedSegmentIndex] == 0){ /* Up button */ NSLog(@"Up"); } else if ([paramSender selectedSegmentIndex] == 1){ |
/* Down button */ NSLog(@"Down"); } } - (void)viewDidLoad{ [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.title = @"First Controller"; NSArray *items = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"UpArrow.png"], [UIImage imageNamed:@"DownArrow.png"], nil]; UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:items]; segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.momentary = YES; [segmentedControl addTarget:self action:@selector(segmentedControlTapped:) forControlEvents:UIControlEventValueChanged]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: segmentedControl]; } |
|
同样,如果是个自定义的按钮也可以使用类似上面的方法.