[UIView beginAnimations:@"ViewRemove" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView setAnimationDuration:0.3];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
myView.center = CGPointMake(myView.center.x, myView.center.y + 480);
[UIView commitAnimations];
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if ([animationID isEqualToString:@"ViewRemove"]) {
[myView removeFromSuperview];
}
}
缺點:字符串標識易出錯、上下文傳遞麻煩、無法捕獲局部變量、代碼分散。
[UIView animateWithDuration:0.3
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
myView.center = CGPointMake(myView.center.x, myView.center.y + 480);
}
completion:^(BOOL finished) {
if (finished) {
[myView removeFromSuperview];
}
}];
優勢:
myView、self 等finished 為 BOOL,無需字符串比對animateWithDuration 實現序列
+ (void)animateWithDuration:(NSTimeInterval)duration
delay:(NSTimeInterval)delay
options:(UIViewAnimationOptions)options
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion;
| 參數 | 說明 |
|---|---|
| duration | 動畫時長(秒) |
| delay | 延遲啟動時間 |
| options | 曲線/重複/自動反轉/佈局等組合:UIViewAnimationOptionCurveLinear/EaseIn/EaseOut/EaseInOutUIViewAnimationOptionRepeat/AutoreverseUIViewAnimationOptionAllowUserInteractionUIViewAnimationOptionLayoutSubviews |
| animations | 可動畫屬性:frame/bounds/center/transform/alpha/backgroundColor 等 |
| completion | 動畫結束回調,finished=YES 表示正常完成,NO 表示被打斷 |
[UIView animateWithDuration:0.5
delay:0
usingSpringWithDamping:0.6
initialSpringVelocity:0.8
options:UIViewAnimationOptionCurveLinear
animations:^{
view.transform = CGAffineTransformMakeScale(1.2, 1.2);
}
completion:nil];
// 序列
[UIView animateWithDuration:0.3 animations:^{
view.alpha = 0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 animations:^{
view.transform = CGAffineTransformMakeTranslation(0, -100);
}];
}];
// 並行
[UIView animateWithDuration:0.3 animations:^{
view.alpha = 0;
view.transform = CGAffineTransformMakeScale(0.5, 0.5);
}];
// 嵌套 (iOS 8+)
[UIView animateWithDuration:0.3 animations:^{
view.alpha = 0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.2 animations:^{
innerView.alpha = 0;
}];
}];
beginAnimations/commitAnimations 替換為 animateWithDuration:...setAnimationDelegate: / setAnimationDidStopSelector:context void* 改為閉包捕獲對象finished 參數處理中斷情況