I want to create an extension to UISlider that will allow me to use a callback to perform an action when the slider value has changed. In other words, it would have the same effect of adding an action using UIControl.Event.valueChanged.
So instead of adding an action like this:
let mySlider = UISlider()
mySlider.addTarget(self, action: #selector(sliderDidChangeValue(_:)), for: .valueChanged)
@objc func sliderDidChangeValue(_ sender: UISlider) {
print(sender.value)
}
I want to create an extension like this, but one where the callback behaves the same as the action above:
extension UISlider {
convenience init(value: Float = 0,
range: ClosedRange<Float> = 0 ... 1,
callback: @escaping (_ x: Float) -> Void = { _ in}) {
self.init()
self.value = value
self.minimumValue = range.lowerBound
self.maximumValue = range.upperBound
}
}
let mySlider = UISlider(value: 10, range: 1...10) { (newValue) in
print(newValue)
}
It seems to me it should be possible to implement, but I'm really not sure how to go about it. Thanks in advance for any help.