anon
anon

Reputation:

Passing function to variable so it can be called later on

I am currently working on making a custom UIView class for an app i am working on, and it requires that you pass a void that will be executed upon the tap event of the UIView. What i need to be able to do, is take the function that was passed to the init() function, and store it so it can be called later. The code that i am working on currently looks like this:

class CustomUIView: UIView {

    private var _tapListener : Void;

    init (tapListener: () -> Void){
        //Attempt to set _tapListener variable as tap listener does not work :(
        _tapListener = tapListener();
        //Right now it just executes the function :(
        let listener = UITapGestureRecognizer(target: self, action: #selector(callFunction));
        self.addGestureRecognizer(listener)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func callFunction() {
        //Call the function here
        _tapListener();
    }
}

How is it possible to accomplish what i am trying to do here?

Any and all help is greatly appreciated

Upvotes: 1

Views: 60

Answers (2)

janusfidel
janusfidel

Reputation: 8106

Consider using closures:

typealias tapListenerClosure = () -> Void

class CustomUIView: UIView {

    var tapClosure: tapListenerClosure

    init (tap: @escaping tapListenerClosure) {
        self.tapClosure = tap
        super.init(....
        let listener = UITapGestureRecognizer(target: self, action: #selector(callFunction));
        self.addGestureRecognizer(listener)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func callFunction() {
        //Call the function here
        self.tapClosure()
    }
}

Upvotes: 2

Paolo
Paolo

Reputation: 3955

Just define your instance variable in the same way as the argument to init:

private var _tapListener: () -> Void

Upvotes: 3

Related Questions