Reputation: 15
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
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):
addTarget(_:action:for:)
with your helper func as the targetIf you want to support different UIControlEvent
s, 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