ios导航栏默认只有左右两个位置放置按钮,用Master-Detil模板生成的MasterViewController就是个例子。但是到SDK5.0以后就可以给左右两个位置放置NSArray的多个按钮了。这也是最简洁的方式,不用使用UISegmentedControl这东西的按钮都是连在一起的明显不是我想要的,可参考:http://2015.iteye.com/blog/1583386。也不用使用UIToolbar,这东西也麻烦,还得注意背景色。
如果从xib拖动进了按钮,手动连接好了函数,那么如下是最简单的用法:
[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects: firstButton,secondButton,nil]];
如果想纯代码搞定,那么:
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"first" style:UITabBarSystemItemContacts target:self action:@selector(one:)];
UIBarButtonItem *anotherButton2 = [[UIBarButtonItem alloc] initWithTitle:@"second" style:UITabBarSystemItemContacts target:self action:@selector(two:)];
[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects: anotherButton,anotherButton2,nil]];
[anotherButton release];
[anotherButton2 release];
这和android的原理是一样的,不想用xml布局,那么就用代码搞定,只不过不符合MVC的设计。
不过还遇到一个问题:
如果是这样
@synthesize firstButton = _firstButton;
接下来使用firstButton发现是空指针,而_firstButton却是真正的指针。难道=还可以掏出对象的内容?
后来看了这篇文章才明白了:http://blog.csdn.net/pinklpig/article/details/7379779
这种用法还有个好处,如果不明确指明私有变量的话,系统就会认为你的私有变量名和属性名是一样的。那么使用起来就是
self.firstButton, 引用计数加1,所以如果不想引用计数增加的话。你懂得。。。