2015-05-07 56 views
-1

我正在嘗試動畫UIImageView,基本上在原始位置整個視圖都在屏幕上。只要按下按鈕,視圖應該向左滑動並保持可見,只是其中的一部分。用於constraint.constant的值是:約束動畫無法正常工作Swift

  1. 在屏幕上的位置= 0(這是起始位置
  2. 關屏幕位置= -200(這應該是到達點)

這裏的代碼。

func constraintAnimation (duration: Double, animatedConstraint: NSLayoutConstraint, finalConstantValue: CGFloat) { 

    self.view.layoutIfNeeded() 
    UIImageView.animateWithDuration(duration, animations: { 
    animatedConstraint.constant = finalConstantValue 

    }) 
    self.view.layoutIfNeeded() 
    println("") 

} 
+0

我以前使用過這一點,這只是工作正常,現在出現了問題。問題是:視圖實際到達位置,但沒有合適的持續時間。任何人都知道我錯過了什麼..? – Waveseller

+0

不要爲常量中的變化設置動畫。爲'layoutIfNeeded()'調用動畫。 – matt

回答

4

更改您的代碼這一點,並嘗試

func constraintAnimation (duration: Double, animatedConstraint: NSLayoutConstraint, finalConstantValue: CGFloat) { 
    animatedConstraint.constant = finalConstantValue 
    UIImageView.animateWithDuration(duration, animations: { 
    self.view.layoutIfNeeded() 
    }) 
    println("") 
} 
+0

我試過你的代碼,但仍然是同樣的問題,UIImageView移動到左側,但沒有動畫.... – Waveseller

+0

我在我的Mac上測試它,它工作得很好。請將代碼關於如何調用此方法。 – Leo

+0

更新:所以你的代碼實際上工作。如果我在主ViewController中聲明這個函數,並在同一個文件的代碼中調用它,它就可以工作。但是我試圖做的是組織我的項目:我創建了一個新的類SwiftController:UIViewController。我宣佈並實現了那裏的功能,並試圖在主ViewController中調用它。我想這個錯誤在這裏。我希望這對你有意義。非常感謝! – Waveseller

1

嘗試以這種方式寫作,下面是客觀-C

[UIButton animateWithDuration:0.5 animations:^{ 
    self.horizontalConstraint.constant+=150; 
    [self.checkbut layoutIfNeeded]; 
} completion:^(BOOL finished) { 

}]; 

您的代碼動畫按鈕的簡單例子

func constraintAnimation (duration: Double, animatedConstraint: NSLayoutConstraint, finalConstantValue: CGFloat) { 

UIImageView.animateWithDuration(duration, animations: { 
animatedConstraint.constant = finalConstantValue//Set the constant relative to initial positon like i have didi in above example 
self.view.layoutIfNeeded() 
}) 
println("") 

}

+0

非常感謝,我認爲問題在於類之間的關係。這個函數在另一個swift文件中聲明 – Waveseller