How to enable “tap and slide” in a UISlider?

后端 未结 14 542
不知归路
不知归路 2020-12-03 20:54

What I want to get is a UISlider which lets the user not only slide when he starts on its thumbRect, but also when he taps elsewhere. When the user

14条回答
  •  醉梦人生
    2020-12-03 21:44

    I didn't check David Williames answer, but I'll post my solution in case someone is looking for another way to do it.

    Swift 4

    First create a custom UISlider so that it will detect touches on the bar as well :

    class CustomSlider: UISlider {
        override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
            return true
        }
    }
    

    (don't forget to set your slider to be this CustomSlider, on storyboard)

    The on viewDidLoad of the view controller that is displaying the slider:

    self.slider.addTarget(self, action: #selector(sliderTap), for: .touchDown)
    

    (this is only used to pause the player when moving the slider)

    Then, on your UISlider action:

    @IBAction func moveSlider(_ sender: CustomSlider, forEvent event: UIEvent) {
        if let touchEvent = event.allTouches?.first {
            switch touchEvent.phase {
                case .ended, .cancelled, .stationary:
                    //here, start playing if needed
                    startPlaying()                    
                default:
                    break
            }
        }
    }
    

    And on your "sliderTap" selector method:

    @objc func sliderTap() {
        //pause the player, if you want
        audioPlayer?.pause()
    }
    

    Suggestion: set the player "currentTime" before starting to play:

    private func startPlaying() {
        audioPlayer?.currentTime = Double(slider.value)
        audioPlayer?.play()
    }
    

提交回复
热议问题