Call function outside of class from UIButton

你离开我真会死。 提交于 2019-12-10 20:13:17

问题


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.

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)

Edit: 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
   }
}

Thanks in advance!


回答1:


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.




回答2:


You can find here a complete tutorial. https://github.com/fatihyildizhan/SingletonFunctionForAddTarget

if you don't want do download it:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var btnGotoVacation: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        btnGotoVacation.addTarget(MySingletonClass.sharedInstance, action: Selector("visitBodrum:"), forControlEvents:.TouchUpInside)
    }
}

class MySingletonClass:NSObject {
    static let sharedInstance = MySingletonClass()

    func visitBodrum(sender:AnyObject) {
        print("don't forget to visit yalikavak :) ")
    }
}

The key point is that you should inherit your singleton class from NSObject.

if not you'll probably get this error:

and if you do:




回答3:


You would have to pass a reference of the class that contains the function. For example, if you are using a singleton pattern:

button.addTarget(FunctionEngine.sharedInstance, action: "buttonFunction", ...


来源:https://stackoverflow.com/questions/27848144/call-function-outside-of-class-from-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!