我正在尝试创建一个方法,该方法利用UIView的"+ animateWithDuration:animations:completion"方法来执行动画,并等待完成.我很清楚我可以在完成块中放置通常会出现的代码,但我想避免这种情况,因为在包含更多动画之后会有大量代码,这会让我看到嵌套块.
我尝试使用信号量实现如下方法,但我不认为这是最好的方法,特别是因为它实际上不起作用.谁能告诉我我的代码有什么问题,和/或实现同一目标的最佳方法是什么?
+(void)animateAndWaitForCompletionWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations
{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[UIView animateWithDuration:duration
animations:animations
completion:^(BOOL finished) {
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
Run Code Online (Sandbox Code Playgroud)
我不确定我的代码有什么问题但是当我调用下面显示的方法时,完成块永远不会运行,我最终陷入困境.
[Foo animateAndWaitForCompletionWithDuration:0.5 animations:^{
//do stuff
}];
Run Code Online (Sandbox Code Playgroud)
- - - - - - - - - - - - - - - - - - - - - -编辑 - - - -------------------------------------------
如果有人遇到类似问题,您可能会对我使用的代码感兴趣.它使用递归来使用每个完成块,而不必嵌套每个函数调用.
+(void)animateBlocks:(NSArray*)animations withDurations:(NSArray*)durations {
[Foo animateBlocks:animations withDurations:durations atIndex:0];
}
+(void)animateBlocks:(NSArray*)animations withDurations:(NSArray*)durations atIndex:(NSUInteger)i {
if (i < [animations count] && i < [durations count]) {
[UIView …Run Code Online (Sandbox Code Playgroud) semaphore objective-c ios objective-c-blocks animatewithduration