iOS的Core Animation動(dòng)畫網(wǎng)上一抓一大把宜狐,寫的都很好
比如這個(gè)(太詳細(xì)了蛀缝,我都懶得看完):
Core Animation編程指南 - 士夢 - 博客園
還有這個(gè)
iOS開發(fā)基礎(chǔ)知識:Core Animation(核心動(dòng)畫) - 簡書
最近有個(gè)需求冯乘,想要?jiǎng)赢嫿Y(jié)束后把視圖刪除掉,那么就需要在動(dòng)畫結(jié)束后判斷是否是當(dāng)前動(dòng)畫塔橡,以防誤刪。
Core Animation結(jié)束后霜第,layer會回到原來的狀態(tài)葛家。設(shè)置fillMode參數(shù)為不還原動(dòng)畫
animation.fillMode = @"forwards";
動(dòng)畫結(jié)束的回調(diào):
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
}
其實(shí)用過的同學(xué)都知道,在這個(gè)方法中使用anim是無法得到動(dòng)畫的庶诡,因?yàn)镃ore Animation動(dòng)畫默認(rèn)執(zhí)行完會刪除惦银。那么就要設(shè)置動(dòng)畫結(jié)束后不刪除:
animation.removedOnCompletion = NO;
現(xiàn)在就可以在stop回調(diào)中得到動(dòng)畫了。如果您已經(jīng)懂了末誓,下面就不用看了
完整的步驟
-
在SB中創(chuàng)建一個(gè)用于移動(dòng)的小view扯俱,和點(diǎn)擊開始動(dòng)畫的小按鈕。綁定按鈕點(diǎn)擊事件
SB - 在點(diǎn)擊事件中為小view創(chuàng)建動(dòng)畫
-(IBAction)animationAction:(UIButton *)sender {
CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"position"];
[animation setDuration:0.5];
// 設(shè)置delegate
animation.delegate = self;
// 動(dòng)畫結(jié)束后不刪除動(dòng)畫喇澡,否則在回調(diào)中無法得到動(dòng)畫
animation.removedOnCompletion = NO;
// 設(shè)置動(dòng)畫不還原
animation.fillMode = @"forwards";
[animation setFromValue:[NSValue valueWithCGPoint:CGPointMake(_aView.center.x, 150)]];
[animation setToValue:[NSValue valueWithCGPoint:CGPointMake(_aView.center.x, 350)]];
[self.aView.layer addAnimation:animation forKey:@"anim"]; // key 用來標(biāo)識動(dòng)畫
}
- 動(dòng)畫結(jié)束回調(diào)迅栅,不刪除了,這里改變背景色
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
if([self.aView.layer animationForKey:@"anim"] == anim) { // 根據(jù)上面的標(biāo)識的key來判斷動(dòng)畫
_aView.backgroundColor = [UIColor blackColor];
}
}
效果
效果