在为 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();
}];
}
这是解决这个问题的正确方法吗?我想我一直在避免它,因为我不熟悉块的使用(甚至不确定我是否正确地声明了该块),这似乎是一个简单问题的复杂解决方案。