當iOS編程,我經常發現自己面臨着以下情況:iOS方法調用動畫,完成時執行操作?
- (void)someMethod
{
[self performSomeAnimation];
//below is an action I want to perform, but I want to perform it AFTER the animation
[self someAction];
}
- (void)performSomeAnimation
{
[UIView animateWithDuration:.5 animations:^
{
//some animation here
}];
}
面對這種情況,我通常最終只是複製/粘貼我的動畫代碼,這樣我就可以使用完成塊處理,像這樣:
- (void)someMethod
{
[self performSomeAnimation];
//copy pasted animation... bleh
[UIView animateWithDuration:.5 animations:^
{
//same animation here... code duplication, bad.
}
completion^(BOOL finished)
{
[self someAction];
}];
}
- (void)performSomeAnimation
{
[UIView animateWithDuration:.5 animations:^
{
//some animation here
}];
}
解決此問題的正確方法是什麼?我是否應該將一塊代碼傳遞給我的-(void)performSomeAction
方法,如下所示,並在完成動畫時執行該塊?
- (void)someMethod
{
block_t animationCompletionBlock^{
[self someAction];
};
[self performSomeAnimation:animationCompletionBlock];
}
- (void)performSomeAnimation:(block_t)animationCompletionBlock
{
[UIView animateWithDuration:.5 animations:^
{
//some animation here
}
completion^(BOOL finished)
{
animationCompletionBlock();
}];
}
難道是解決這個問題的正確方法嗎?我想我一直在避免它,因爲我不熟悉塊的使用(甚至不確定是否正確地聲明瞭該塊),並且它似乎是一個簡單問題的複雜解決方案。
你說的動畫總是相同的,但完成變化?如果是這樣,你的解決方案對我來說看起來很不錯。 –
我認爲我的語法不正確。我只是看着它,我應該像這樣聲明我的塊:void(^ myBlock)(void),但是我的方法聲明看起來像什麼? - (void)performSomeAnimation :(無效)(^ myBlock)(void)似乎沒有工作(我敢肯定我正在屠殺語法哈哈) – MikeS