2013-12-12 47 views
1

我将代码添加到ViewController的viewDidLoad方法中。我有两个UIBarButtonItem,其中一个在左边叫做Left,另一个在右边叫Right。我可以让左边的按钮工作,但我甚至看不到正确的按钮。我究竟做错了什么?如何以编程方式添加两个UIBarButtonItem的UINavigationBar?

UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 420,   44)]; 
[navbar setBackgroundImage:[UIImage imageNamed:@"bg_fade.png"]  forBarMetrics:UIBarMetricsDefault]; 
UINavigationItem *item = [[UINavigationItem alloc]initWithTitle:@"Tray Tracker"]; 
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithTitle:@"Left" style:UIBarButtonItemStylePlain target:self action: 
          @selector(leftAction:)]; 
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action: 
           @selector(saveAction:)]; 
item.leftBarButtonItem = leftButton; 
item.rightBarButtonItem = rightButton; 
navbar.items = @[item]; 
[self.view addSubview:navbar]; 

我确实有leftAction和saveAction

swcreenshot http://imageshack.com/a/img560/5706/skve.png

回答

1

的IBActions如果你只是想有两个按钮的那一栏,你应该使用一个UIToolbar代替。处理这个简单的案例要容易得多。您需要做的唯一更改就是创建一个UIBarButtonItem flexibleSpace(这是一个系统项目),并致电[toolbar setItems:@[leftButton, flexibleSpace, rightButton]];

如果您需要实际的导航功能,例如后退按钮,请查看此答案。你需要使用UINavigationBar pushNavigationItem。

using UINavigationBar without UINavigationController

在你的榜样,你是滥用项目属性。对于UINavigationBar的状态的文档,

The bottom item is at index 0, the back item is at index n-2, 
and the top item is at index n-1, where n is the number of items in the array. 

为了做到完成你想用UINavigationBar的做什么,我认为你需要多navigationItems。

使用UIToolbar或将UINavigationBar与UINavigationController结合使用会更容易。

编辑 既然您发布了图片,我认为您看不到正确的栏按钮的原因是因为您的框架宽度太大。 iPhone的屏幕是320像素宽,所以你的导航栏的框架应该是CGRectMake(0,0,320,44)

+0

我以前使用过UIToolbar,它工作的很棒。我将研究UINavigationController。 – Pramesh

+0

查看我的编辑。我认为你的问题仅仅是酒吧框架 – adamF

+0

这是做到了。接得好 – Pramesh

相关问题