简体   繁体   中英

Call function outside of class from UIButton

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!

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:

在此输入图像描述

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

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", ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM