做 iOS 動畫時常有一個需求:動畫播完之後,接著做某件事,例如把遮罩視圖移除。實作上有兩種主流寫法。
舊式的 UIView 動畫 API 透過 delegate 與 selector 來回呼:
[UIView beginAnimations:nil context:nil]; // 指定動畫代理與結束後要呼叫的方法 [UIView setAnimationDelegate:self]; // removeCover 就是動畫結束後要執行的方法 [UIView setAnimationDidStopSelector:@selector(removeCover)]; self.coverBtn.alpha = 0.0; [UIView commitAnimations];
對應的回呼實作:
- (void)removeCover
{
[self.coverBtn removeFromSuperview];
self.coverBtn = nil;
}
這種寫法在早期專案中很常見,缺點是邏輯被拆成兩塊,而且 selector 是字串形式,拼錯時編譯器不會提醒,只能等 runtime 才發現。
從 iOS 4 開始,蘋果提供了帶 completion block 的動畫方法,把「動畫」與「動畫結束後要做的事」寫在同一處:
[UIView animateWithDuration:1.0
animations:^{
self.coverBtn.alpha = 0.0;
self.iconbtn.frame = self.oldPicFrame;
}
completion:^(BOOL finished) {
[self.coverBtn removeFromSuperview];
self.coverBtn = nil;
}];
新專案一律建議使用 Block 版本,理由有三點:
finished 參數,可以判斷動畫是自然播完還是被中途取消,避免誤刪畫面元素。動畫代理那套 API 已被標記為 deprecated,除非維護老專案,否則沒有理由繼續使用。