2017-06-06 83 views
0

工作基本上我只需添加上ImageView的是UICollectionViewCell的子視圖一個簡單的旋轉動畫,動畫工作正常,但是當我滾動集合視圖和向後滾動,動畫只是採空。如何解決這個問題呢? 這是我添加到imageView。如何保持動畫上UICollectionView

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation") 
rotationAnimation.fromValue = 0.0 
rotationAnimation.toValue = Double.pi 
rotationAnimation.duration = 2.0 
rotationAnimation.repeatCount = .infinity 
view.layer.add(rotationAnimation, forKey: nil) 
+0

當您添加此動畫?您的代碼需要更多上下文。 – jrturton

+0

我將它添加到func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell – Xie

回答

1

爲了避免滾動的影響,需要使用Runloop及其commonModes,使動畫與CADisplayLink可以做到這一點:

private var _displayLinkForRotation:CADisplayLink? 
var displayLinkForRotation:CADisplayLink { 
    get{ 
     if _displayLinkForRotation == nil { 
      _displayLinkForRotation = CADisplayLink(target: self, selector: #selector(excuteAnimations)) 
      _displayLinkForRotation?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes) 
     } 
     return _displayLinkForRotation! 
    } 
} 

func excuteAnimations() { 
    //This function will be called 60 times per second. 
    //According to your question, you have 2 seconds to rotate the view to 180 angle. So we rotate 90 angle per second here. 
    //self.view could be replaced by another view you want to rotate. 
    self.view.transform = self.view.transform.rotated(by: 90.0/60.0/180.0 * CGFloat.pi) 

    let angle = atan2(self.view.transform.b, self.view.transform.a) * (45.0/atan(1.0)) 
    if (round(angle) >= 180.0) { //Stop when rotated 180 angle 
     self.displayLinkForRotation.isPaused = true 
    } 
} 

要啓動動畫:

self.displayLinkForRotation.isPaused = false 

摧毀它:

self.displayLinkForRotation.invalidate() 
_displayLinkForRotation = nil 
+0

感謝您的回覆!如你所知,我想它添加到UICollectionView下ImageView的,所以我修改功能FUNC excuteAnimations(查看:UIView的),但後來我得到一個錯誤「終止應用程序由於未捕獲的異常‘NSInvalidArgumentException’,原因是:「 - [CADisplayLink變換]:無法識別的選擇發送到實例0x1742028c0' 」 – Xie

+0

不要使用參數來傳遞圖,使用全局變量的ImageView代替。該參數將把CADisplayLink本身傳遞給該函數。 –

+0

這就像我想的動畫添加到集合視圖一些imageview的,所以好像我不能在這裏使用全局變量? – Xie

0

由於初始化rotationAnimation 變線

view.layer.add(rotationAnimation, forKey: nil) 

,當你還沒有添加動畫的關鍵,你使用哪個

view.layer.add(rotationAnimation, forKey: "transform.rotation") 

希望它可以幫助