爲了避免滾動的影響,需要使用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
當您添加此動畫?您的代碼需要更多上下文。 – jrturton
我將它添加到func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell – Xie