如何在 xcode 中以编程方式向按钮添加操作
我知道如何通过从界面生成器中拖动来将 IBAction 添加到按钮,但我想以编程方式添加操作以节省时间并避免不断地来回切换。解决方案可能非常简单,但当我搜索时,我似乎找不到任何答案。谢谢你!
I know how to add an IBAction to a button by dragging from the interface builder, but I want to add the action programmatically to save time and to avoid switching back and forth constantly. The solution is probably really simple, but I just can't seem to find any answers when I search it. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
试试这个:
首先将其写入 viewcontroller 的 .h 文件中
现在将其写入 viewcontrollers viewDidLoad 的 .m 文件中。
在视图控制器的 .m 文件中编写这个外部 viewDidLoad 方法
try this:
first write this in your .h file of viewcontroller
Now write this in your .m file of viewcontrollers viewDidLoad.
write this outside viewDidLoad method in .m file of your view controller
对于 Swift 3
首先为按钮操作创建一个函数,然后将该函数添加到您的按钮目标
For Swift 3
Create a function for button action first and then add the function to your button target
UIButton
继承自UIControl
。它具有添加/删除操作的所有方法: UIControl 类参考。请参阅“准备和发送操作消息”部分,其中涵盖了– sendAction:to:forEvent:
和– addTarget:action:forControlEvents:
。UIButton
inherits fromUIControl
. That has all of the methods to add/remove actions: UIControl Class Reference. Look at the section "Preparing and Sending Action Messages", which covers– sendAction:to:forEvent:
and– addTarget:action:forControlEvents:
.iOS 14 SDK:
您可以添加带有关闭回调的操作:
获取对控件发送者的引用
来源
IOS 14 SDK:
you can add action with closure callback:
Getting a reference to the control sender
source
试试这个:
Swift 4
Objective-C
您可以在 Apple 文档中找到丰富的信息源。看一下 UIButton 的文档,它会显示 UIButton 是 UIControl, 实现了 添加目标。
--
需要注意
myAction
后面是否加冒号action:@selector(myAction)
这是参考。
Try this:
Swift 4
Objective-C
You can find a rich source of information in Apple's Documentation. Have a look at the UIButton's documentation, it will reveal that UIButton is a descendant of UIControl, which implements the method to add targets.
--
You'll need to pay attention to whether add colon or not after
myAction
inaction:@selector(myAction)
Here's the reference.
快速回答:
文档: https://developer.apple.com/documentation/uikit /uicontrol/1618259-addtarget
Swift answer:
Documentation: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget