从UIButton的类外部调用函数 [英] Call function outside of class from UIButton

查看:93
本文介绍了从UIButton的类外部调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在按下按钮时调用的函数,但是与迄今为止我所做的一切不同,我希望能够从多个ViewController中的任何一个访问它.我不想在每个ViewController中重复相同的代码块.

I have a function that I'd like to call when a button is pressed, but unlike anything I've done to date, I'd like to be able to reach it from any of several ViewControllers. I don't want to have to duplicate the same chunk of code in each ViewController.

我尝试定义要在ViewController类之外调用的函数,但是我无法弄清楚要达到该目标需要设置什么.通常使用self是因为该函数是在类中定义的,但是如果该函数在另一个文件中和/或一个类之外,该怎么办?

I've tried defining the function I want to call outside of the ViewController class, but I can't figure out what I need to set the target to be in order to reach it. Typically self is used because the function is defined within the class, but what do you do if the function in another file and/or outside of a class?

button.addTarget(???, action: "myFunction:", forControlEvents: UIControlEvents.TouchUpInside)

我将能够使用的另一种解决方案是执行类似的操作,并在创建按钮的函数中定义要调用的函数,但是我遇到了一个同样的问题,即不知道必须做到这一点.

Another solution I would be able to use would be to do something like this and define the function I want to call inside the function that creates the button, but I run into the same problem of not knowing what the target needs to be to reach it.

class ViewController {
    // Main code here
}

func makeButton() {
   //  Code to make button here
   button.addTarget(???, action: "buttonPressed",...)

   func buttonPressed() {
       // Code that runs when the button is pressed goes here
   }
}

提前谢谢!

推荐答案

通常,您将创建另一个类并在其中实现您的代码,然后创建(并保留)该类的实例并将其设置为目标.

You would usually create another class and implement your code there, then create (and keep) an instance of the class and set it as the target.

这篇关于从UIButton的类外部调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆