UISlider set value



我有一个UISlider,我想将其值设置为从1到10。我使用的代码是.

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

我想做的是制作UISlider的动画,这样它需要0.5秒才能改变。我不想让它变得更光滑。

到目前为止,我的想法是。

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)

我正在Swift中寻找解决方案。

已编辑

经过一些讨论,我想我应该澄清两种建议解决方案之间的差异:

  1. 使用内置的UISlider方法.setValue(10.0, animated: true)
  2. 将此方法封装在UIView.animateWithDuration

由于作者明确要求进行0.5s的更改——可能由另一个操作触发——因此第二种解决方案更可取。

例如,考虑一个按钮连接到一个将滑块设置为其最大值的动作。

@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)
}

运行一个仅存在UISliderUIButton对象的简单UIVIewController应用程序会产生以下结果。

  • 方法1:即时幻灯片(即使animated: true
  • 方法2:制作过渡动画。请注意,如果我们在此上下文中设置animated: false,则转换将是瞬时的

@dfri的答案的问题是蓝色最小跟踪器正在从100%移动到值,所以为了解决这个问题,你需要稍微改变一下方法:

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)
    }
  }
}

最新更新