Aakash Sarang
Aakash Sarang

Reputation: 15

passing multiple closures as parameters to a function in swift

So I am trying to pass two closures to a function which creates a subview. The main part of function that takes closures as arguments and calls them is as follows:

///goButton and cancelButton are class level variables

var goButton = UIButton(type: .system)

var cancelButton = UIButton(type: .system)


func addSubViewWithAction(_ titleString:String, _ button1Text:String, _ button2Text:String, closureYes:@escaping ()->(), closureNo:@escaping ()->()) {

goButton.actionHandle(controlEvents: UIControlEvents.touchUpInside,
                      ForAction:closureYes)

cancelButton.actionHandle(controlEvents: UIControlEvents.touchUpInside,
                          ForAction:closureNo)
}

here is how I am trying to call it.

addSubViewWithAction("Hide Penguin here?","Yes","Cancel", closureYes: switchPlayers, closureNo: deletePenquin)

The problem is that it calls the deletePenguin function for both the buttons and never calls the switchPlayers function.

here is how I am adding buttons to main view through subview

    //v here is a UIView object
    //Add all buttons and text to subView
    v.addSubview(titleField)
    v.addSubview(goButton)
    v.addSubview(cancelButton)
    v.layer.cornerRadius = 8

    //Add subView to main view
    window.addSubview(v)

Upvotes: 1

Views: 572

Answers (1)

Andreas Oetjen
Andreas Oetjen

Reputation: 10199

The problem is that actionHandle somehow works statically, so it will overwrite any previous assignment with the most recent one.

You could do the following (no complete code solution here, only pseudo-code):

  • Subclass UIButton
  • Add an instance variable that holds the closure to be executed
  • Add an instance (helper) func that acts as the target for your event and inside executes the closure above
  • Create a func that takes the closure to be excecuted as a parameter. Inside,
    • Assign your instance variable with the provided closure
    • Call addTarget(_:action:for:) with your helper func as the target

If you want to support different UIControlEvents, you'll have to improve those steps a little, maybe by using a dictionary that maps the event to the closure or so.

Upvotes: 1

Related Questions