W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
之前提到過(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è)置removedOnCompletion
為NO
,如果你設(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
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: