On iOS, you're not setting a listener; you add a target (an object) and an action (method signature, "selector" in iOS parlance) to your UIControl (which UIButton is a subclass of):button1.addTarget(self, action: "buttonClicked:", for: .touchUpInside)button2.addTarget(self, action: "buttonClicked:", for: .touchUpInside)button3.addTarget(self, action: "buttonClicked:", for: .touchUpInside)第一个参数是目标对象,在本例中为 self.动作是一个选择器(方法签名),基本上有两个选项(稍后会详细介绍).控制事件 有点特定于 UIControl - .TouchUpInside 通常用于点击按钮.The first parameter is the target object, in this case self. The action is a selector (method signature) and there are basically two options (more on that later). The control event is a bit specific to the UIControl - .TouchUpInside is commonly used for tapping a button.现在,行动.这是以下格式之一的方法(名称由您选择):Now, the action. That's a method (the name is your choice) of one of the following formats:func buttonClicked()func buttonClicked(_ sender: AnyObject?)要使用第一个,请使用buttonClicked",对于第二个(您想要的),请使用buttonClicked:"(带有尾随冒号).sender 将是事件的来源,换句话说,就是你的按钮.To use the first one use "buttonClicked", for the second one (which you want here) use "buttonClicked:" (with trailing colon). The sender will be the source of the event, in other words, your button.func buttonClicked(_ sender: AnyObject?) { if sender === button1 { // do something } else if sender === button2 { // do something } else if sender === button3 { // do something }}(这里假设 button1、button2 和 button3 是实例变量).(this assumes that button1, button2 and button3 are instance variables).考虑为每个按钮使用单独的方法,而不是使用大 switch 语句的这种方法.根据您的具体用例,两种方法都可能更好:Instead of this one method with the big switch statement consider using separate methods for each button. Based on your specific use case either approach might be better:func button1Clicked() { // do something}func button2Clicked() { // do something}func button3Clicked() { // do something}在这里,我什至没有使用 sender 参数,因为我不需要它.Here, I'm not even using the sender argument because I don't need it.P.S.:您可以在 Storyboard 或 nib 文件中添加目标和操作,而不是以编程方式添加.为了公开您将 IBAction 放在函数前面的操作,例如:P.S.: Instead of adding targets and actions programmatically you can do so in your Storyboard or nib file. In order to expose the actions you put IBAction in front of your function, e.g.:@IBAction func button1Clicked() { // do something} 这篇关于在 Swift 中以编程方式设置动作侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-06 19:56