Search code examples
iosswiftuislider

How to build the UISlider automatic slide by itself in Swift?


In purpose, I want to set the UISlider will auto slide by self to use in video player. I try to find the solution by research and follow that code, but it's still not work. Everyone have any solution with this here is my code.

override func awakeFromNib() {
      self.sldTime.maximumValue = 10
      self.sldTime.minimumValue = 0
      self.sldTime.continuous = true
      self.sldTime.addTarget(self, action: #selector(self.sliderAutoChange), forControlEvents: .ValueChanged)
}

func sliderAutoChange() {
    let index = Float(self.sldTime.value + 1)   // increase by 1
    self.sldTime.setValue(index, animated: false)
    print("index \(index)")
} 

When I debug it, it seem like the sliderAutoChange() function do not call.


Solution

  • If you want to change Slider value automatically then you can use NSTimer like this.

    override func awakeFromNib() {
        self.sldTime.maximumValue = 10
        self.sldTime.minimumValue = 0
        self.sldTime.continuous = true
    
        NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.updateSlider(_:), userInfo: nil, repeats: true)      
    }
    
    func updateSlider(timer: NSTimer) {
    
        let index = Float(self.sldTime.value + 1)   // increase by 1
        self.sldTime.setValue(index, animated: true)
        print("index \(index)")
        if self.sldTime.value >= self.sldTime.maximumValue {
              timer.invalidate()
        }
    }