2014-10-27 97 views
0

我無法搞清楚如何讓動畫工作。我有一個名爲BallView的UIView。我可以畫一個很大的紅色圓圈。我希望這個圈子從紅色變爲綠色。我在我的視圖的初始化器中設置了CAShapeLayerCABasicAnimation,但動畫不起作用。這裏是我的初始化:CAShapeLayer沒有動畫

- (void)initHelper:(UIColor*)c {  
    CAShapeLayer* sl = (CAShapeLayer*) self.layer; 
    sl.fillColor = [UIColor redColor].CGColor; 
    sl.path = [[UIBezierPath bezierPathWithOvalInRect:self.bounds] CGPath]; 

    CABasicAnimation *colorAnim = [CABasicAnimation animationWithKeyPath:@"fillColor"]; 
    colorAnim.duration = 5.0; 
    colorAnim.fromValue = [UIColor redColor]; 
    colorAnim.toValue = [UIColor greenColor]; 
    colorAnim.repeatCount = 10; 
    colorAnim.autoreverses = YES; 
    [sl addAnimation:colorAnim forKey:@"fillColor"]; 
} 
+0

你在哪裏調用此方法?它是BallView的初始化方法嗎? – gabbler 2014-10-27 01:39:04

+0

我重寫了其他init方法。那些init方法調用initHelper。 – csnate 2014-10-27 01:40:38

回答

2

你從和值是不正確的,你應該設置

colorAnim.fromValue = (__bridge id)[UIColor redColor].CGColor; 
colorAnim.toValue = (__bridge id)[UIColor greenColor].CGColor; 
0

你不應該把動畫中的init方法,因爲當時這個觀點是被添加到視圖層次結構中。嘗試將initHelper方法從init方法中移出並在BallView.h中公開,因此您可以在視圖Controller中隨時調用它,您可以將其添加到viewDidAppear方法中。如果你不想這樣做,你可以簡單地推遲initHelper這樣的火時間:

[self performSelector:@selector(initHelper:) withObject:nil afterDelay:2.0];