将按钮添加到自定义导航栏

时间:2012-08-09 18:16:00

标签: iphone objective-c ios

在我的viewDidLoad方法中,我有以下内容:

navigBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemAction target:self action:@selector(btnClicked:)];
[self.view addSubview:navigBar];

该按钮根本不显示!我错过了什么?

3 个答案:

答案 0 :(得分:4)

// create the navigation bar and add it to the view
UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:navigationBar];

// create a button
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemAction target:self action:@selector(btnClicked:)];

// create a UINavigationItem and add the button in the right hand side
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:nil];
navItem.rightBarButtonItem = button;

// add the UINavigationItem to the navigation bar
[navigationBar pushNavigationItem:navItem animated:NO];

答案 1 :(得分:3)

在导航栏上设置按钮。然后在导航上创建BarButtonItem

barbutton=[UIBarButtonItem alloc] ]initWithTitle......
navigation.navigationController.rightBarButton= barbutton;

答案 2 :(得分:3)

首先阅读:

  

当您使用导航栏作为独立对象时,您负责提供其内容。与其他类型的视图不同,您不直接将子视图添加到导航栏。而是使用导航项(UINavigationItem类的实例)来指定要显示的按钮或自定义视图。导航项具有用于指定导航栏左侧,右侧和中心的视图以及指定自定义提示字符串的属性。

     

导航栏管理一堆UINavigationItem对象。虽然堆栈主要用于支持导航控制器,但您也可以使用它来实现自己的自定义导航界面。堆栈中最顶部的项表示导航项,其内容当前由导航栏显示。使用pushNavigationItem:animated:方法将新导航项目推送到堆栈,并使用popNavigationItemAnimated:方法从堆栈中弹出项目。为了用户的利益,这些更改都可以进行动画处理。

基本上你需要做的是:

[navigBar pushNavigationItem:self.navigationItem animated:NO];