如何在 xcode 中以编程方式向按钮添加操作

How do you add an action to a button programmatically in xcode(如何在 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 中以编程方式向按钮添加操作

基础教程推荐