Reputation: 2409
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!
Upvotes: 3
Views: 4515
Reputation: 8832
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
fromNSObject
.
if not you'll probably get this error:
and if you do:
Upvotes: 6
Reputation: 80271
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", ...
Upvotes: 2
Reputation: 119041
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.
Upvotes: 3