Tap on UISlider to Set the Value

前端 未结 6 418
無奈伤痛
無奈伤痛 2021-02-01 19:20

I created a Slider (operating as control of the video, like YouTube has at the bottom) and set the maximum (duration) and minimum values. And then used SeekToTime t

6条回答
  •  情歌与酒
    2021-02-01 19:50

    Looks like you need to actually initialize the tap gesture recognizer in your viewDidLoad() per the code example above. There's a comment there, but I don't see the recognizer being created anywhere.

    Swift 2:

    class ViewController: UIViewController {
    
        var slider: UISlider!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Setup the slider
    
            // Add a gesture recognizer to the slider
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "sliderTapped:")
            self.slider.addGestureRecognizer(tapGestureRecognizer)
        }
    
        func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
            //  print("A")
    
            let pointTapped: CGPoint = gestureRecognizer.locationInView(self.view)
    
            let positionOfSlider: CGPoint = slider.frame.origin
            let widthOfSlider: CGFloat = slider.frame.size.width
            let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)
    
            slider.setValue(Float(newValue), animated: true)      
        }
    }
    

    Swift 3:

    class ViewController: UIViewController {
    
        var slider: UISlider!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Setup the slider
    
            // Add a gesture recognizer to the slider
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(gestureRecognizer:)))
            self.slider.addGestureRecognizer(tapGestureRecognizer)
        }
    
        func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
            //  print("A")
    
            let pointTapped: CGPoint = gestureRecognizer.location(in: self.view)
    
            let positionOfSlider: CGPoint = slider.frame.origin
            let widthOfSlider: CGFloat = slider.frame.size.width
            let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)
    
            slider.setValue(Float(newValue), animated: true)
        }
    }
    

提交回复
热议问题