如何在运行时设置 UIBarButtonItem 的目标和操作
尝试过这个,但仅适用于 UIButton:
[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
Tried this but only works for UIButton:
[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
只需直接设置 UIBarButtonItem 的
target
和action
属性即可。Just set the UIBarButtonItem's
target
andaction
properties directly.UIBarButtonItem 没有相同的 addTarget 方法,因此您必须直接设置它们,如下所示
......
UIBarButtonItem doesnt have the same addTarget method so you have to set them directly as follows
...
设置
UIBarButtonItem
的target
和action
Swift 5 & 4
Set
target
andaction
of yourUIBarButtonItem
Swift 5 & 4
我遇到了类似的问题...我假设您的意思是,如果您的 UIButton 不是 UITabBar 的一部分来调用 btnClicked 那么它可以正常工作。如果这是您提出的问题,请检查您的 btnClicked 方法并将其从: 更改
为该
方法,并在头文件中声明 btnClicked...
对于它的价值,这就是我在 tabbarbuttonitem 中设置按钮的方式:
I ran into a similar problem... I assume you mean that if your UIButton is not part of your UITabBar to call btnClicked then it works appropriately. If this is the problem you are proposing then, check your btnClicked method and change it from:
to
that, and declare btnClicked in the header file...
For what it's worth, this is how I setup a button in tabbarbuttonitem:
如果您在代码中需要多次这样做,那么最好继续扩展
UIBarButtonItem
,我在下面用 Swift 完成了这一点。 :)举个例子,使用 self 作为
UIViewController
,您只需调用:If you need this enough times in your code, it's nice to go ahead and extend
UIBarButtonItem
which I've done below in Swift. :)As an example, with self as a
UIViewController
, you'd simply call:对于自定义
UIBarButtonItem
,这是可行的。您将目标和操作设置为要添加到
UIBarButtonItem
的按钮。For a custom
UIBarButtonItem
this works.You set the target and action to the button that you are adding to your
UIBarButtonItem
.@wp42 今天确实有效。
在 Objective-C 中执行此操作的一个巧妙方法是向 UIBarButtonItem 类添加一个类别:
.h 文件
.m 文件
在实践中:
@wp42 It does work today.
A nifty way of doing this in objective-C is adding a category to UIBarButtonItem class:
.h file
.m file
In practice:
对于自定义视图:使用
UITapGestureRecognizer
并将isUserInteractionEnabled
设置为true
。For custom views: use an
UITapGestureRecognizer
and set upisUserInteractionEnabled
totrue
.如果您以编程方式添加 UIBarButtonItem,设置目标和操作的最佳方法是使用以下方法之一初始化按钮:
If you are programmatically adding the UIBarButtonItem, the best way to set the target and action is to initialize the button with one of the following methods:
Swift 5:
提取到扩展:
在代码中调用:
操作:
向此工厂添加新按钮非常容易。
Swift 5:
Extract to extensions:
Call in code:
Action:
Pretty easy to add new buttons to this factory.
您可能想尝试 addTarget 方法。
You may want to try out the addTarget method.