First, let me state that I am not looking for a solution that is stated here. This one solves it using inheritance, but I cannot use that, as my needs are to have a composition solution.
I basically want to send more parameters when doing addTarget to a UIControl
, using composition. I actually already have something working, but I am not sure at all if it's good practice, what are the drawbacks, and if there is another solution that is simpler. I'm hoping you can help me with that. Here is the solution. I basically wrap the control in a class that takes in the extra params and a closure that is called when the value changes.
class ControlWithParameters {
var control: UIControl
var extraParam: String
var valueChanged: (UIControl, String) -> ()
required init(_ control: UIControl, _ extraParam: String, _ valueChanged: @escaping (UIControl, String) -> ()) {
self.control = control
self.extraParam = extraParam
self.valueChanged = valueChanged
control.addTarget(self, action: #selector(valueChanged(sender:)), for: .valueChanged)
}
@objc internal func valueChanged(sender: UIControl) {
self.valueChanged(sender, self.extraParam)
}
}
let slider = UISlider()
let extraParam = "extraParam"
let controlWithParameters = ControlWithParameters(slider, extraParam, valueChanged)
func valueChanged(_ control:UIControl, _ extraParam: String) {
print(extraParam)
}
Is this a good solution? I can't know if this memory efficient or not, and I don't know if I'm complicating myself for this simple task. Any help is appreciated!