2015-12-16 29 views
-2

我有一個UISlider,我想設置它的值從1到10.我使用的代碼是。UISlider設定值

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

我想要做的是動畫UISlider,以便它需要0.5s來改變。我不想讓它變得更加平滑。

我到目前爲止的想法是。

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」的文檔嗎?有一種用動畫設置值的方法。 – rmaddy

+0

這個問題基本上是http://stackoverflow.com/questions/20539913/uiview-animatewithduration-not-working-with-uislider的副本,只是答案(儘可能簡單)在Objective-C中。 – rmaddy

+0

@rmaddy謝謝你的一切,我覺得你已經爲我回答了很多問題。你非常慷慨的時間和幫助人們在這裏,我很欣賞這一點。 –

回答

4

EDITED

經過一番討論後,我想我應該澄清這兩個建議的解決方案之間的差異:

  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應用程序。

  • Method 1:即時幻燈片(即使animated: true
  • Method 2:動畫處理的過渡。請注意,如果我們在此上下文中設置animated: false,則轉換將是即時的。
+1

爲什麼不直接使用'UISlider'提供的方法來動態改變值呢? – rmaddy

+1

查看@rmaddy的評論 –

+0

謝謝你們,我發現它,答案已被編輯。 –

1

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