【问题标题】:How to add Navigation Bar "Plus" button, and use it in code如何添加导航栏“加号”按钮,并在代码中使用
【发布时间】:2015-01-13 17:13:36
【问题描述】:

我在导航控制器中有一个表格视图,顶部有一个导航栏。我想在此导航栏的右侧添加一个加号按钮,并在按下该按钮时发布 NSLog。但是,所有建议以编程方式添加导航栏的在线资源都失败了。我该怎么做?

感谢所有帮助。

编辑:这是我在 viewDidLoad 方法中使用的一些代码。所以你知道,我只是添加了这段代码,没有做任何其他事情:

UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(doSave:)];
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release];  

编辑 2:当我创建项目时,在 Interface Builder 中,我创建了一个导航控制器,将我的 FirstViewController 左侧的箭头移动到导航控制器,然后删除了我的 FirstViewController。这会阻止代码工作吗?

【问题讨论】:

  • 发布一些你尝试过的代码——机会是最简单的修复是你已经尝试过的实现中的一些小错误。

标签: ios objective-c uinavigationcontroller uinavigationbar rightbarbuttonitem


【解决方案1】:

在你的 ViewController 的 viewDidLoad 中:

UIBarButtonItem *plusButton = [[UIBarButtonItem alloc]initWithTitle:@"+" style:UIBarButtonItemStylePlain target:self action:@selector(plusButtonHit)];
self.navigationItem.rightBarButtonItem = plusButton;

-(void)plusButtonHit {
   // do something
   NSLog(@"Log something");
}

如果您想使用图像,只需使用图像而不是文本创建条形按钮。

【讨论】:

  • 我试过了,但什么也没做 :( i.imgur.com/gzZXYXp.png - 我在主帖的编辑下方添加了一部分 - 你认为这会导致我的代码无法工作吗?跨度>
  • 您是否在界面生成器中为视图控制器设置了类?单击顶部的第一个图标(ViewController),在右侧选择身份检查器,然后在类下将其设置为您的视图控制器。
  • 尚未设置为 ViewController;但是,当我输入“ViewController”并按 Enter 时,它什么也没做。我取消选择,然后再次选择,文本消失了。但是,如果我使用新的视图控制器执行此操作,则可以毫无问题地设置类:|
  • 那是你的问题。我的代码工作正常,但 ViewController 不知道它是 ViewController 类型的。
  • 非常感谢!在我离开之前,您知道为什么下拉菜单不起作用吗?我尝试过删除派生数据、清理项目等,但实际上我不能将 View Controller 设置为自定义类,也不能设置任何其他类。该菜单适用于单个视图控制器,但是:\
【解决方案2】:
- (void)viewDidLoad {
    [super viewDidLoad];
     
    UIBarButtonItem *plusButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(plusButtonHit)];
    self.navigationItem.rightBarButtonItem = plusButton;
}

- (void)plusButtonHit {
    NSLog(@"Log something");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    相关资源
    最近更新 更多