使用目标c中的信号量创建执行动画并等待完成的方法

ufm*_*ike 2 semaphore objective-c ios objective-c-blocks animatewithduration

我正在尝试创建一个方法,该方法利用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 animateWithDuration:[(NSNumber*)durations[i] floatValue]
                          animations:(void(^)(void))animations[i]
                          completion:^(BOOL finished){
             [Foo animateBlocks:animations withDurations:durations atIndex:i+1];
         }];
    } 
}
Run Code Online (Sandbox Code Playgroud)

可以像这样使用

[Foo animateBlocks:@[^{/*first animation*/},
                     ^{/*second animation*/}]
     withDurations:@[[NSNumber numberWithFloat:2.0],
                     [NSNumber numberWithFloat:2.0]]];
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 9

在iOS 7及更高版本中,人们通常会使用关键帧动画来实现此效果.

例如,两个动画序列由四个独立的动画组成,每个动画占整个动画的25%,每个动画序列如下所示:

[UIView animateKeyframesWithDuration:2.0 delay:0.0 options:UIViewKeyframeAnimationOptionRepeat animations:^{
    [UIView addKeyframeWithRelativeStartTime:0.00 relativeDuration:0.25 animations:^{
        viewToAnimate.frame = ...;
    }];
    [UIView addKeyframeWithRelativeStartTime:0.25 relativeDuration:0.25 animations:^{
        viewToAnimate.frame = ...;
    }];
    [UIView addKeyframeWithRelativeStartTime:0.50 relativeDuration:0.25 animations:^{
        viewToAnimate.frame = ...;
    }];
    [UIView addKeyframeWithRelativeStartTime:0.75 relativeDuration:0.25 animations:^{
        viewToAnimate.frame = ...;
    }];
} completion:nil];
Run Code Online (Sandbox Code Playgroud)

在早期的iOS版本中,您可以通过几种方式排队一系列动画,但我建议您避免在主线程上使用信号量.

一种方法是将动画包装在并发NSOperation子类中,这在动画完成之前不会完成.然后,您可以将动画添加到自己的自定义串行队列中:

NSOperationQueue *animationQueue = [[NSOperationQueue alloc] init];
animationQueue.maxConcurrentOperationCount = 1;

[animationQueue addOperation:[[AnimationOperation alloc] initWithDuration:1.0 delay:0.0 options:0 animations:^{
    viewToAnimate.center = point1;
}]];

[animationQueue addOperation:[[AnimationOperation alloc] initWithDuration:1.0 delay:0.0 options:0 animations:^{
    viewToAnimate.center = point2;
}]];

[animationQueue addOperation:[[AnimationOperation alloc] initWithDuration:1.0 delay:0.0 options:0 animations:^{
    viewToAnimate.center = point3;
}]];

[animationQueue addOperation:[[AnimationOperation alloc] initWithDuration:1.0 delay:0.0 options:0 animations:^{
    viewToAnimate.center = point4;
}]];
Run Code Online (Sandbox Code Playgroud)

AnimationOperation子类可能看起来像:

//  AnimationOperation.h

#import <Foundation/Foundation.h>

@interface AnimationOperation : NSOperation

- (instancetype)initWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations;

@end
Run Code Online (Sandbox Code Playgroud)

//  AnimationOperation.m

#import "AnimationOperation.h"

@interface AnimationOperation ()

@property (nonatomic, readwrite, getter = isFinished)  BOOL finished;
@property (nonatomic, readwrite, getter = isExecuting) BOOL executing;

@property (nonatomic, copy) void (^animations)(void);
@property (nonatomic) UIViewAnimationOptions options;
@property (nonatomic) NSTimeInterval duration;
@property (nonatomic) NSTimeInterval delay;

@end

@implementation AnimationOperation

@synthesize finished  = _finished;
@synthesize executing = _executing;

- (instancetype)initWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations {
    self = [super init];
    if (self) {
        _animations = animations;
        _options    = options;
        _delay      = delay;
        _duration   = duration;
    }
    return self;
}

- (void)start {
    if ([self isCancelled]) {
        self.finished = YES;
        return;
    }

    self.executing = YES;

    [self main];
}

- (void)main {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:self.duration delay:self.delay options:self.options animations:self.animations completion:^(BOOL finished) {
            [self completeOperation];
        }];
    });
}

#pragma mark - NSOperation methods

- (void)completeOperation {
    if (self.isExecuting) self.executing = NO;
    if (!self.isFinished) self.finished = YES;
}

- (BOOL)isAsynchronous {
    return YES;
}

- (BOOL)isExecuting {
    @synchronized(self) { return _executing; }
}

- (BOOL)isFinished {
    @synchronized(self) { return _finished; }
}

- (void)setExecuting:(BOOL)executing {
    if (_executing != executing) {
        [self willChangeValueForKey:@"isExecuting"];
        @synchronized(self) { _executing = executing; }
        [self didChangeValueForKey:@"isExecuting"];
    }
}

- (void)setFinished:(BOOL)finished {
    if (_finished != finished) {
        [self willChangeValueForKey:@"isFinished"];
        @synchronized(self) { _finished = finished; }
        [self didChangeValueForKey:@"isFinished"];
    }
}

@end
Run Code Online (Sandbox Code Playgroud)

在上面的演示中,我使用了一个串行队列.但您也可以使用并发队列,但使用NSOperation依赖关系来管理各种动画操作之间的关系.这里有很多选择.


如果要取消动画,则可以执行以下操作:

CALayer *layer = [viewToAnimate.layer presentationLayer];
CGRect frame = layer.frame;                // identify where it is now
[animationQueue cancelAllOperations];      // cancel the operations
[viewToAnimate.layer removeAllAnimations]; // cancel the animations
viewToAnimate.frame = frame;               // set the final position to where it currently is
Run Code Online (Sandbox Code Playgroud)

如果需要,您也可以将其合并到操作中的自定义cancel方法中.