99re热视频这里只精品,久久久天堂国产精品女人,国产av一区二区三区,久久久精品成人免费看片,99久久精品免费看国产一区二区三区

8.4 在動(dòng)畫過(guò)程中取消動(dòng)畫

2018-02-24 15:07 更新

在動(dòng)畫過(guò)程中取消動(dòng)畫

之前提到過(guò),你可以用-addAnimation:forKey:方法中的key參數(shù)來(lái)在添加動(dòng)畫之后檢索一個(gè)動(dòng)畫,使用如下方法:

- (CAAnimation *)animationForKey:(NSString *)key;

但并不支持在動(dòng)畫運(yùn)行過(guò)程中修改動(dòng)畫,所以這個(gè)方法主要用來(lái)檢測(cè)動(dòng)畫的屬性,或者判斷它是否被添加到當(dāng)前圖層中。

為了終止一個(gè)指定的動(dòng)畫,你可以用如下方法把它從圖層移除掉:

- (void)removeAnimationForKey:(NSString *)key;

或者移除所有動(dòng)畫:

- (void)removeAllAnimations;

動(dòng)畫一旦被移除,圖層的外觀就立刻更新到當(dāng)前的模型圖層的值。一般說(shuō)來(lái),動(dòng)畫在結(jié)束之后被自動(dòng)移除,除非設(shè)置removedOnCompletionNO,如果你設(shè)置動(dòng)畫在結(jié)束之后不被自動(dòng)移除,那么當(dāng)它不需要的時(shí)候你要手動(dòng)移除它;否則它會(huì)一直存在于內(nèi)存中,直到圖層被銷毀。

我們來(lái)擴(kuò)展之前旋轉(zhuǎn)飛船的示例,這里添加一個(gè)按鈕來(lái)停止或者啟動(dòng)動(dòng)畫。這一次我們用一個(gè)非nil的值作為動(dòng)畫的鍵,以便之后可以移除它。-animationDidStop:finished:方法中的flag參數(shù)表明了動(dòng)畫是自然結(jié)束還是被打斷,我們可以在控制臺(tái)打印出來(lái)。如果你用停止按鈕來(lái)終止動(dòng)畫,它會(huì)打印NO,如果允許它完成,它會(huì)打印YES。

清單8.15是更新后的示例代碼,圖8.6顯示了結(jié)果。

清單8.15 開始和停止一個(gè)動(dòng)畫

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic, strong) CALayer *shipLayer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //add the ship
    self.shipLayer = [CALayer layer];
    self.shipLayer.frame = CGRectMake(0, 0, 128, 128);
    self.shipLayer.position = CGPointMake(150, 150);
    self.shipLayer.contents = (__bridge id)[UIImage imageNamed: @"Ship.png"].CGImage;
    [self.containerView.layer addSublayer:self.shipLayer];
}

- (IBAction)start
{
    //animate the ship rotation
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation";
    animation.duration = 2.0;
    animation.byValue = @(M_PI * 2);
    animation.delegate = self;
    [self.shipLayer addAnimation:animation forKey:@"rotateAnimation"];
}

- (IBAction)stop
{
    [self.shipLayer removeAnimationForKey:@"rotateAnimation"];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //log that the animation stopped
    NSLog(@"The animation stopped (finished: %@)", flag? @"YES": @"NO");
}

@end

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)