简体   繁体   中英

UISlider set value

I have a UISlider and I want to set its value from 1 to 10. The code I use is.

let slider = UISlider()
slider.value = 1.0
// This works I know that
slider.value = 10.0

What I want to do is animate the UISlider so that it takes 0.5s to change. I don't want it to be as jumpy more smooth.

My idea so far is.

let slider = UISlider()
slider.value = 1.0
// This works I know that
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animation: { slider.value = 10.0 } completion: nil)

I am looking for the solution in Swift.

EDITED

After some discussion, I thought I'd clarify the differences between the two suggested solutions:

  1. Using the built-in UISlider method .setValue(10.0, animated: true) .
  2. Encapsulating this method in a UIView.animateWithDuration .

Since the author is asking explicitly for a change that will take 0.5s---possibly triggered by another action---the second solution is to prefer.

As an example, consider that a button is connected to an action that sets the slider to its maximum value.

@IBOutlet weak var slider: UISlider!

@IBAction func buttonAction(sender: AnyObject) {
    // Method 1: no animation in this context
    slider.setValue(10.0, animated: true)

    // Method 2: animates the transition, ok!
    UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: {
        self.slider.setValue(10.0, animated: true) },
        completion: nil)
}

Running a simple single UIVIewController app with just the UISlider and UIButton objects present yields the following results.

  • Method 1 : Instant slide (even though animated: true )
  • Method 2 : Animates transition. Note that if we set animated: false in this context, the transition will be instantaneous.

the problem with @dfri's answer is that the blue Minimum Tracker is moving from 100% to the value, so in order to solve that, you need to change the method a little bit:

extension UISlider
{
  ///EZSE: Slider moving to value with animation duration
  public func setValue(value: Float, duration: Double) {
    UIView.animateWithDuration(duration, animations: { () -> Void in
      self.setValue(self.value, animated: true)

      }) { (bol) -> Void in
        UIView.animateWithDuration(duration, animations: { () -> Void in
          self.setValue(value, animated: true)
          }, completion: nil)
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM