2017-04-25 22 views
1

有很多類似這樣的帖子,我見過,並沒有任何作品。我需要無限旋轉一個視圖,直到被告知停止

這是我的代碼到目前爲止。

func startRotating(view : UIImageView, rotating : Bool) { 

    //Rotating the rotatingClockBarImage 
    UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveLinear], animations: { 

     view.transform = CGAffineTransform(rotationAngle: CGFloat.pi) 

    }, completion: {finished in 

     UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveLinear], animations: { 

      view.transform = CGAffineTransform(rotationAngle: 0) 

     }, completion: nil) 
    })//End of rotation 

    continueRotating(view: view) 

} 

最初的問題是我無法旋轉360度。我想通過旋轉半路和另一半完成。

現在的問題是一旦這個動畫完成,就是這樣。我試圖把它放在while循環中,for循環,來回調用兩個相似的函數。沒有任何工作,只是凍結我的應用程序。例如,在運行3次的for循環中,我放了一個print()。打印寫入控制檯三次,但動畫只發生一次。正因爲如此,我認爲動畫只是在它開始之前就將其自身關閉,而最終的旋轉是唯一可以播放的動畫。所以我需要找到一種方法讓它可以播放每一個旋轉。

這應該不難,看到蘋果的飛機在遊戲應用程序中的Xcode的舊版本中旋轉得如此輕鬆。我試圖避免刪除並重新安裝舊版本,以便我可以查看該代碼。

回答

4

實際上,它會更容易:

extension UIView { 
    func rotate360Degrees(duration: CFTimeInterval = 1.0) { 
     let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") 
     rotateAnimation.fromValue = 0.0 
     rotateAnimation.toValue = CGFloat.pi * 2 
     rotateAnimation.duration = duration 
     rotateAnimation.repeatCount = Float.infinity 
     self.layer.add(rotateAnimation, forKey: nil) 
    } 

    func stopRotating(){ 
     self.layer.sublayers?.removeAll() 
     //or 
     self.layer.removeAllAnimations() 
    } 
} 

然後旋轉: yourView.rotate360Degrees()

停止: yourView。 stopRotating()

+0

我不熟悉「圖層」部分。我基本上將你的代碼複製並粘貼到我的程序中,並試圖使其適用於所有工作,但我得到錯誤「ViewController沒有成員'層'」。正因爲如此,我在嘗試調用它時也出現錯誤。當我寫'myView'.rotate360Degrees()它有一個錯誤,說「UIImageView沒有成員'rotate360Degrees'」。 – AdrianGutierrez

+0

它是一個擴展,你需要做的是將所有的代碼粘貼到你的類之外。然後你使用它像imageView.rotate().. – ankit

+0

所以我複製和粘貼你的代碼以外的類。 (在我的導入和我的課程之間),它說「使用未解析的標識符'self'」。對不起,如果這些都是明顯的問題,我還是習慣了這個。儘管感謝您的幫助。 – AdrianGutierrez

-1

您是否嘗試在下半輪完成塊中再次調用startRotating?

請注意,如果您想讓它停止,您應該使用自己的「停止」標誌有條件地執行此操作。

+0

是的,我試過了,其實我終於找到了一種方式來不斷讓它循環我的方式,但它只是越來越快,直到應用程序最終會凍結。 – AdrianGutierrez

相關問題