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 中以编程方式向按钮添加操作
基础教程推荐
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
