How do you add an action to a button programmatically in xcode(如何在 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!
推荐答案
试试这个:
斯威夫特 4
myButton.addTarget(self,
action: #selector(myAction),
for: .touchUpInside)
Objective-C
[myButton addTarget:self
action:@selector(myAction)
forControlEvents:UIControlEventTouchUpInside];
您可以在 Apple 的文档中找到丰富的信息来源.看一下UIButton的文档,会发现UIButton是UIControl, 实现了 添加目标.
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.
--
需要注意myAction
后面是否加冒号action:@selector(myAction)
You'll need to pay attention to whether add colon or not after myAction
in
action:@selector(myAction)
这是参考.
这篇关于如何在 xcode 中以编程方式向按钮添加操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 xcode 中以编程方式向按钮添加操作


- GPS状态的广播接收器? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- URL编码Swift iOS 2022-01-01
- UITextView 内容插图 2022-01-01