2013-04-01 189 views
0

我使用iOS核心動畫「CABasicAnimation」爲UIImageView設置動畫,所有工作都適合我,但唯一的問題是當完成動畫後動畫到位置回到原來的位置。我怎麼能克服這個?我需要保持UIImageView移動位置。iOS「CABasicAnimation」在動畫完成後將組件移動到原始位置

注:我已經看到了幾個有關這方面的成功答案的問題,但我不知道爲什麼我的工作不像他們說的那樣工作。

After rotating a CALayer using CABasicAnimation the layer jumps back to it's unrotated position

這裏是我的示例代碼,

CGPoint endPt = CGPointMake(160, 53); 
    CABasicAnimation *anim5 = [CABasicAnimation animationWithKeyPath:@"position"]; 
    [anim5 setBeginTime:CACurrentMediaTime()+0.4]; 
    anim5.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; 
    anim5.fromValue = [NSValue valueWithCGPoint:imgRef.layer.position]; 
    anim5.toValue = [NSValue valueWithCGPoint:endPt]; 
    anim5.duration = 1.5; 
    anim5.speed = 2; 
    [imgRef.layer addAnimation:anim5 forKey:@"position"]; 

    //this is what other answers ask to do 
    [anim5 setFillMode:kCAFillModeForwards]; 
    [anim5 setRemovedOnCompletion:NO]; 

BTW [imgRef.layer setPosition:CGPointMake(160, 53)];不會幫我,因爲我推遲動畫與4毫秒。

回答

3

其根本原因是動畫只是在兩個值之間轉換屬性,它實際上並沒有改變結束值。動畫完成時需要更改結束值,有三種方法可以實現。 1)使用CAAnimation超類的委託屬性通知動畫何時完成。此時您可以將屬性設置爲最終值。請參閱:https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CAAnimation_class/Introduction/Introduction.html#//apple_ref/occ/cl/CAAnimation animationDidStop:finished:是您需要在委託上實現的方法。 2)在周圍的CATransaction上設置完成塊。您需要手動啓動CATransaction,而不是讓CABasicAnimation爲您自動執行。請參閱:Objective-C - CABasicAnimation applying changes after animation? 3)見OMZ的評論如下...

+1

有一個更好的(更簡單)的方法:http://oleb.net/blog/2012/11/prevent-caanimation-snap-back/ – omz

+0

謝謝,omz,你的解決方案修復我的問題 –

+0

我也謝謝! – skinsfan00atg

1

正確的答案是,設置圖層的位置屬性,但如你所指出的,這使得它更困難,因爲你想0.4秒的延遲在職位變更之前。是否有任何理由不能先執行延遲,然後再進行動畫製作?類似這樣的:

- (IBAction)didTapMove:(id)sender 
{ 
    [self performSelector:@selector(animate) withObject:nil afterDelay:0.4]; 
} 

- (void)animate 
{ 
    CGPoint endPt = CGPointMake(160, 53); 
    CABasicAnimation *anim5 = [CABasicAnimation animationWithKeyPath:@"position"]; 
    anim5.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; 
    anim5.fromValue = [NSValue valueWithCGPoint:_imageView.layer.position]; 
    anim5.toValue = [NSValue valueWithCGPoint:endPt]; 
    anim5.duration = 1.5; 
    anim5.speed = 2; 

    [_imageView.layer addAnimation:anim5 forKey:@"position"]; 

    [_imageView.layer setPosition:CGPointMake(160, 53)]; 
} 

注意我已經從動畫中刪除了開始時間,因爲在執行選擇器調用中發生延遲。

+0

謝謝@Matt,你的回答是正確的,但這不是我想要的。這個答案不適合我的情況,因爲我有很多動畫在一起,所以我真的需要從「CABasicAnimation」延遲。 –

相關問題