【问题标题】:UISlider set valueUISlider 设置值
【发布时间】:2015-12-16 15:11:19
【问题描述】:

我有一个 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 中的解决方案。

【问题讨论】:

标签: ios swift user-interface uislider uianimation


【解决方案1】:

已编辑

经过一番讨论,我想我应该澄清两个建议的解决方案之间的区别:

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

由于作者明确要求更改将花费 0.5 秒——可能由另一个动作触发——第二个解决方案是首选。

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

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

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

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

【讨论】:

  • 为什么不直接使用UISlider提供的方法来动画化值变化呢?
  • 谢谢大家,我找到了答案。
  • 没有理由在UIView animateWithDuration 块内使用setValue:animated:
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多