[英]CABasicAnimation instead of UIView animation
我有以下動畫塊,做一些字幕標簽效果。
我有兩個標簽,我滾動兩個,當滾動動畫完成后,我設置新幀並再次滾動。 動畫永遠不會停止。
- (void)scrollAwayWithInterval:(NSTimeInterval)interval delay:(NSTimeInterval)delay {
[UIView animateWithDuration:interval
delay:delay
options:UIViewAnimationOptionCurveLinear
animations:^{
self.label.frame = _labelDestRect;
self.subLabel.frame = _subLabelDestRect;
}
completion:^(BOOL finished) {
if (finished) {
if (self.subLabel.frame.origin.x > 0) {
[self prepareFramesForStep2];
} else {
[self prepareFramesForStep1];
}
[self scrollAwayWithInterval:interval delay:delay];
}
}];
}
我需要一種暫停/恢復動畫的方法,所以我想用CABasicAnimation
做同樣的動畫。
所以我的問題是,使用CABasicAnimation
進行以下動畫的等效方法是什么?
實際上可以暫停UIView動畫。 它的工作原理是因為在幕后,iOS會在您正在制作動畫的視圖層上創建CAAnimations。 我在github上有一個名為KeyframeViewAnimations的示例項目,它正是如此。
如果要同時為2個不同的視圖設置動畫,則可能需要在包含兩個視圖的superview圖層上操作speed屬性,或者分別在兩個視圖的圖層上暫停動畫。 (我之前沒有嘗試在多個視圖上暫停UIView動畫,所以我不完全確定在superview的圖層上設置speed屬性是否有效。)
編輯:我剛嘗試過,在superview的圖層上設置速度會暫停兩個動畫。 我在暫停/恢復按鈕上設置的暫停/恢復代碼如下所示:
- (IBAction)handlePauseButton:(UIButton *)sender
{
animationIsPaused = !animationIsPaused;
if (animationIsPaused)
{
[pauseButton setTitle: @"Resume" forState: UIControlStateNormal];
CALayer *theLayer = animationContainerView.layer;
//Freeze the animation.
theLayer.speed = 0;
//Calculate how far we into the animation based on current media time minus the media time when
//The animation started.
//Shift the layer's timing so it appears at the current time.
theLayer.timeOffset = CACurrentMediaTime()-theLayer.beginTime;
theLayer.beginTime = 0;
}
else
{
[pauseButton setTitle: @"Pause" forState: UIControlStateNormal];
CALayer *theLayer = animationContainerView.layer;
CFTimeInterval pausedTime = [theLayer timeOffset];
//Now reset the time offset and beginTime to zero.
theLayer.timeOffset = 0.0;
theLayer.beginTime = 0.0;
//Figure out how much time has elapsed since the animation was paused.
CFTimeInterval timeSincePause = CACurrentMediaTime() - pausedTime;
//Set the layer's beginTime to that time-since-pause
theLayer.beginTime = timeSincePause;
//Start the animation running again
theLayer.speed = 1.0;
}
}
你仍然可以使用這個塊。
您需要添加的是BOOL變量,只需按一下按鈕(或者您想要的話)就可以將其設置為NO,並將其設置為:
- (void)scrollAwayWithInterval:(NSTimeInterval)interval delay:(NSTimeInterval)delay {
[UIView animateWithDuration:interval
delay:delay
options:UIViewAnimationOptionCurveLinear
animations:^{
self.label.frame = _labelDestRect;
self.subLabel.frame = _subLabelDestRect;
}
completion:^(BOOL finished) {
if (finished) {
if (shouldContinueAnimation) {
if (self.subLabel.frame.origin.x > 0) {
[self prepareFramesForStep2];
} else {
[self prepareFramesForStep1];
}
[self scrollAwayWithInterval:interval delay:delay];
}
}
}];
}
shouldContinueAnimation
是你的BOOL。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.