Am trying solution in Swift 4 as suggested by Diogo in Tap on UISlider to Set the Value - on a set of UISliders defined programmatically, but I can't reference the UISlider insider the Selector.
In viewDidLoad() with 'slider' defined as any UISlider in a collection of UISliders running inside a For... statement:
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(_: slider:)))
slider.addGestureRecognizer(tapGestureRecognizer)
Selector:
@objc func sliderTapped(_ gestureRecognizer:UIGestureRecognizer, slider:UISlider) {
let pointTapped: CGPoint = gestureRecognizer.location(in: assessView)
let positionOfSlider: CGPoint = slider.convert(slider.bounds.origin, to: assessView)
let widthOfSlider: CGFloat = slider.bounds.size.width
let moveDistance = sqrt(Double(pow(Double(pointTapped.x - positionOfSlider.x),2) + pow(Double(pointTapped.y - positionOfSlider.y),2)))
var newValue: CGFloat
if pointTapped.x < 10 {
newValue = 0
} else {
newValue = (CGFloat(moveDistance) * CGFloat(slider.maximumValue) / widthOfSlider)
}
slider.setValue(Float(newValue), animated: true)
}
Also, 'slider' is added to a subview under 'assessView' - should this be the target of the taprecogniser?
When printing out the 'slider' in the console it states that 'slider' is uninitialized. Any reflections on how to deal with this?
You can't create your own arbitrary signature for the selector used in a target/selector pair.
Update your selector to only take the gesture. You can get the slider from the gesture.
You also need to check the state of the gesture.
Update your setup:
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped))
slider.addGestureRecognizer(tapGestureRecognizer)
Then update your method:
@objc func sliderTapped(_ gesture: UITapGestureRecognizer) {
guard gesture.state == .ended else { return }
guard let slider = gesture.view as? UISlider else { return }
let pointTapped: CGPoint = gesture.location(in: assessView)
let positionOfSlider: CGPoint = slider.convert(slider.bounds.origin, to: assessView)
let widthOfSlider: CGFloat = slider.bounds.size.width
let moveDistance = sqrt(Double(pow(Double(pointTapped.x - positionOfSlider.x),2) + pow(Double(pointTapped.y - positionOfSlider.y),2)))
var newValue: CGFloat
if pointTapped.x < 10 {
newValue = 0
} else {
newValue = (CGFloat(moveDistance) * CGFloat(slider.maximumValue) / widthOfSlider)
}
slider.setValue(Float(newValue), animated: true)
}