動畫是提質感最直接的手段。在引入第三方動畫庫之前,系統本身提供的 API 其實已經能覆蓋大部分需求,以下整理五種常見寫法。
一、最基礎的 UIView 動畫
[UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:2]; frame.origin.x += 150; [img setFrame:frame]; [UIView commitAnimations];
二、序列影格動畫
把多張圖片放進陣列,交給 UIImageView 播放即可,適合做加載中或逐格動效:
NSArray *myImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"myImage1.png"],
[UIImage imageNamed:@"myImage2.png"],
[UIImage imageNamed:@"myImage3.png"],
[UIImage imageNamed:@"myImage4.png"], nil];
UIImageView *myAnimatedView = [[UIImageView alloc] initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages;
myAnimatedView.animationRepeatCount = 0; // 0 表示無限循環
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
三、CATransition 轉場動畫
Core Animation 提供的轉場,效果比單純位移更有張力:
CATransition *animation = [CATransition animation]; animation.duration = 0.5f; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; animation.fillMode = kCAFillModeForwards; // 轉場類型 // kCATransitionFade / kCATransitionMoveIn / kCATransitionPush / kCATransitionReveal // 轉場方向 // kCATransitionFromRight / kCATransitionFromLeft / kCATransitionFromTop / kCATransitionFromBottom animation.type = kCATransitionPush; animation.subtype = kCATransitionFromRight; [self.view.layer addAnimation:animation forKey:@"animation"];
四、UIView Animations 的翻頁與卷軸效果
[UIView beginAnimations:@"animationID" context:nil]; [UIView setAnimationDuration:0.5f]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationRepeatAutoreverses:NO]; // 四種轉場可選 // [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES]; // [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES]; // [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES]; // [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES]; [UIView commitAnimations];
五、Block 動畫與巢狀串接
這是最推薦的寫法:語法簡潔,而且可以在 completion 中串接下一步動畫。下面這個例子先放大再淡出移除:
[UIView animateWithDuration:1.25 animations:^{
CGAffineTransform newTransform = CGAffineTransformMakeScale(1.2, 1.2);
[firstImageView setTransform:newTransform];
[secondImageView setTransform:newTransform];
} completion:^(BOOL finished) {
[UIView animateWithDuration:1.2 animations:^{
[firstImageView setAlpha:0];
[secondImageView setAlpha:0];
} completion:^(BOOL finished) {
[firstImageView removeFromSuperview];
[secondImageView removeFromSuperview];
}];
}];
選型建議
前兩種(begin/commit 與 CATransition)屬於較早期的寫法,其中 beginAnimations 系列在現代 iOS 已不建議使用,維護老專案時看得到即可。新專案請直接採用 Block 形式的 animateWithDuration:,它支援 spring 阻尼、delay、以及 animateKeyframesWithDuration: 做多段關鍵frame,表達力遠大於舊 API。
另外提醒:動畫只是視覺上的插值,並不會真正改變 model 的值。也就是說,一個 view 動畫位移到新位置後,它的 frame 屬性仍是原值,動畫結束後若沒有做對應的屬性賦值,view 會瞬間跳回原位——這是新手最常遇到的「動畫做完就彈回去」問題。