以编程方式将选择器添加到导航栏按钮
嘿,我正在尝试以编程方式向导航栏中的按钮添加选择器,但我似乎无法找出它根本不起作用的原因。这是我得到的代码:
[self.navigationController.navigationItem.rightBarButtonItem setAction:@selector(showWithLabel)];
我这样做是否正确?还有什么我应该做的吗?
编辑:我发现该按钮是nil
,我不明白,因为它连接到rightBarButton
插座。
编辑(再次):我发现导航项为零,知道问题出在哪里吗?
Hey, I am trying to add a selector to a button in my navigationbar programmatically and I can't seem to find out why it doesn't work at all. Here is the code I got:
[self.navigationController.navigationItem.rightBarButtonItem setAction:@selector(showWithLabel)];
Am I doing this correctly and is there anything else I should do?
EDIT: I found out that the button was nil
, I don't understand as it is connected to rightBarButton
outlet.
EDIT(Again): I found out that the navigationitem is nil, any idea where is the problem then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我曾经这样做过并且工作正常
I use to do that like this and works fine
所以你说 self.navigationController.navigationItem.rightBarButtonItem 是 nil,但是 rightBarButtonItem 在 IB 中是连接的。
造成这种情况的原因有两个:
navigationItem
、navigationController
或self
是nil
。请记住,属性访问表达式实际上是消息表达式。例如,如果
self.navigationController
为nil
,则向其发送navigationItem
消息将返回nil
。不管怎样,如果self.navigationController.navigationItem
为nil
,那么向其询问rightBarButtonItem
将返回nil< /代码>。
检查每一个子表达式 -
self
、self.navigationController
和self.navigationController.navigationItem
- 并查看哪一个是零
。然后,修复那个。So you say
self.navigationController.navigationItem.rightBarButtonItem
isnil
, butrightBarButtonItem
is hooked up in IB.There are two reasons why this could be:
navigationItem
,navigationController
, orself
isnil
.Remember that property access expressions are really message expressions. If, say,
self.navigationController
isnil
, then sending it thenavigationItem
message will returnnil
. If, one way or the other,self.navigationController.navigationItem
isnil
, then asking it for itsrightBarButtonItem
will returnnil
.Check every one of those sub-expressions—
self
,self.navigationController
, andself.navigationController.navigationItem
—and see which one isnil
. Then, fix that one.您还应该设置一个将接收操作的目标(我认为您将使用“self”):
You should set also a target which will receive an action (I think you'll use 'self'):
只需尝试在 viewDidLoad 方法中以编程方式创建 rightBarButtonItem 即可:
Just try to create rightBarButtonItem programmatically in viewDidLoad method:
尝试在选择器名称后添加冒号,如下所示:
Try adding a colon after your selector name, like this: