What is happening in this block queue? - ios

I was searching for a way to queue animation blocks, and happened across this blog post:
http://xibxor.com/2013/03/27/uiview-animation-without-nested-hell/
I can't get it to work, though...the scope of how to arrange those elements isn't clear. Also, what are those semicolons on lines 18, 25, and 32 doing? Can anyone explain how to use this?
EDIT: here is the code copied from the source:
NSMutableArray* animationBlocks = [NSMutableArray new];
typedef void(^animationBlock)(BOOL);
// getNextAnimation
// removes the first block in the queue and returns it
animationBlock (^getNextAnimation)() = ^{
animationBlock block = animationBlocks.count ? (animationBlock)[animationBlocks objectAtIndex:0] : nil;
if (block){
[animationBlocks removeObjectAtIndex:0];
return block;
}else{
return ^(BOOL finished){};
}
};
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
NSLog(#"Multi-step Animation Complete!");
}];
// execute the first block in the queue
getNextAnimation()(YES);

First thanks to share of this post, it's a great idea. That works perfectly for me:
in your .h outside #interface:
typedef void(^animationBlock)(BOOL);
Then in your .m (here it's inside - (void)viewDidLoad):
NSMutableArray* animationBlocks = [NSMutableArray new];
UILabel* labelTest = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
labelTest.text = #"Label Test";
[self.view addSubview:labelTest];
// getNextAnimation
// removes the first block in the queue and returns it
animationBlock (^getNextAnimation)() = ^{
animationBlock block = animationBlocks.count ? (animationBlock)[animationBlocks objectAtIndex:0] : nil;
if (block){
[animationBlocks removeObjectAtIndex:0];
return block;
}else{
return ^(BOOL finished){};
}
};
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:2.0 animations:^{
NSLog(#"1-step Animation Complete!");
labelTest.alpha = 0;
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:2.0 animations:^{
labelTest.text = #"New text";
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:2.0 animations:^{
labelTest.alpha = 1;
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
NSLog(#"Multi-step Animation Complete!");
}];
// execute the first block in the queue
getNextAnimation()(YES);
It's a really simple animation but you need it to test it ^^
Hope that will help.

Related

Change label background color using animation in iOS

I am trying to show an animated n number of level.
There is n number of levels under UIStackView.
What I want:
Using animation
First, change the label 4's background color
Second, change the label 3's background color
Third, change the label 7's background color
.......
nth, change the label background color
What is the problems:
Change all background color instantly without delaying.
#property (nonatomic, strong) IBOutletCollection(UILabel) NSArray *lblArray;
-(void)animationTestIntoLoop {
__block NSMutableArray* animationBlocks = [NSMutableArray new];
typedef void(^animationBlock)(BOOL);
// getNextAnimation
// removes the first block in the queue and returns it
animationBlock (^getNextAnimation)(void) = ^{
if ([animationBlocks count] > 0){
animationBlock block = (animationBlock)[animationBlocks objectAtIndex:0];
[animationBlocks removeObjectAtIndex:0];
return block;
} else {
return ^(BOOL finished){
animationBlocks = nil;
};
}
};
for (UILabel *label in self.lblArray) {
[animationBlocks addObject:^(BOOL finished){
[UIView animateWithDuration:3 delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
//my first set of animations
label.backgroundColor = [UIColor redColor];
} completion: getNextAnimation()];
}];
}
getNextAnimation()(YES);
}
I can't find it documented anywhere, but it appears the backgroundColor property of UILabel is not animatable. This hack appears to work, however, as long as you don't set the background color of the label view itself:
*#import <QuartzCore/QuartzCore.h>*
//Add this in ViewDidLoad
for (UILabel *label in self.lblArray)
{
label.layer.backgroundColor = [UIColor whiteColor].CGColor;
}
-(void)animationTestIntoLoop
{
__block NSMutableArray* animationBlocks = [NSMutableArray new];
typedef void(^animationBlock)(BOOL);
// getNextAnimation
// removes the first block in the queue and returns it
animationBlock (^getNextAnimation)(void) = ^{
if ([animationBlocks count] > 0){
animationBlock block = (animationBlock)[animationBlocks objectAtIndex:0];
[animationBlocks removeObjectAtIndex:0];
return block;
} else {
return ^(BOOL finished){
animationBlocks = nil;
};
}
};
for (UILabel *label in self.lblArray)
{
[animationBlocks addObject:^(BOOL finished){
[UIView animateWithDuration:2.0 animations:^{
label.layer.backgroundColor = [UIColor redColor].CGColor;
} completion:getNextAnimation()];
}];
}
getNextAnimation()(YES);
}

IOS/Objective-c: code reduction within animations

I have this simple animation that fades in several labels, one at a time. But I wonder if it is possible to reduce the code with this logic?
[UIView animateWithDuration:0.50f animations:^{
[_latLabel setAlpha:0.9f];
[_firstLat setAlpha:0.9f];
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.50f animations:^{
[_lonLabel setAlpha:0.9f];
[_firstLon setAlpha:0.9f];
}completion:^(BOOL finished) {
[UIView animateWithDuration:0.50f animations:^{
[_speedLabel setAlpha:0.9f];
[_firstSpeed setAlpha:0.9f];
}completion:^(BOOL finished) {
[UIView animateWithDuration:0.50f animations:^{
[_realNorthLabel setAlpha:0.9f];
[_firstReal setAlpha:0.9f];
}completion:^(BOOL finished) {
[UIView animateWithDuration:0.50f animations:^{
[_magneticNorthLabel setAlpha:0.9f];
[_firstMagnetic setAlpha:0.9f];
}];
}];
}];
}];
}];
Considering the need to perform operation on 2 label objects while executing any single section of the animation block, create a dictionary structure wherein section indexes define the chronological order of the sections animations to be performed & each section index contains an array of label objects.
A simple iterating loop over this structure christened here as dictionaryOfSectionedLabels can help achieve the desired alternate animation implementation.
NSDictionary<NSNumber *, NSArray *> *dictionaryOfSectionedLabels = #{ #0: #[_latLabel, _firstLat],
#1: #[_lonLabel, _firstLon],
#2: #[_speedLabel, _firstSpeed],
#3: #[_realNorthLabel, _firstReal],
#4: #[_magneticNorthLabel, _firstMagnetic]
};
for (NSUInteger i = 0; i < dictionaryOfSectionedLabels.allKeys.count; i++) {
[UIView animateWithDuration:0.5 delay:0.5*i options:UIViewAnimationOptionLayoutSubviews animations:^{
UILabel *firstLabel = [dictionaryOfSectionedLabels[#(i)] firstObject];
UILabel *secondLabel = [dictionaryOfSectionedLabels[#(i)] lastObject];
firstLabel.alpha = 0.9f;
secondLabel.alpha = 0.9f;
} completion:nil];
}
Creating an NSDictionary of your labels can be tedious and confusing code to read in the future. I'd recommend you just create a method.
-(void)customFadeForLabel:(UILabel *)theLabel withDelay:(float)delayAmount {
[UIView animateWithDuration:0.50f
delay:delayAmount
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
[theLabel setAlpha:0.9f];
}completion:nil];
}
Then just call it as needed with delays
[self customFadeForLabel:_latLabel withDelay:0.00f];
[self customFadeForLabel:_firstLat withDelay:0.00f];
[self customFadeForLabel:_lonLabel withDelay:0.50f];
[self customFadeForLabel:_firstLon withDelay:0.50f];
[self customFadeForLabel:_speedLabel withDelay:1.00f];
[self customFadeForLabel:_firstSpeed withDelay:1.00f];
[self customFadeForLabel:_realNorthLabel withDelay:1.50f];
[self customFadeForLabel:_firstReal withDelay:1.50f];
[self customFadeForLabel:_magneticNorthLabel withDelay:2.00f];
[self customFadeForLabel:_firstMagnetic withDelay:2.00f];

Creating a method to perform animations and wait for completion using a semaphore in objective c

I am trying to create a method which makes use of UIView's "+animateWithDuration:animations:completion" method to perform animations, and wait for completion. I am well aware that I could just place the code that would normally come after it in a completion block, but I would like to avoid this because there is a substantial amount of code after it including more animations, which would leave me with nested blocks.
I tried to implement this method as below using a semaphore, but I don't think this is the best way to do it, especially because it doesn't actually work. Can anyone tell me what is wrong with my code, and/or what the best way of achieving the same goal is?
+(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);
}
I'm not sure what's wrong with my code but when I call the method as shown below, the completion block never runs and I end up in limbo.
[Foo animateAndWaitForCompletionWithDuration:0.5 animations:^{
//do stuff
}];
-------------------------------------------EDIT-------------------------------------------------
If anyone is facing a similar issue, you might be interested to see the code I used. It uses recursion to make use of each completion block, without having to nest each function call.
+(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];
}];
}
}
which can be used like so
[Foo animateBlocks:#[^{/*first animation*/},
^{/*second animation*/}]
withDurations:#[[NSNumber numberWithFloat:2.0],
[NSNumber numberWithFloat:2.0]]];
In iOS 7 and later one would generally employ keyframe animation to achieve this effect.
For example, a two second animation sequence that is composed of four separate animations that take up 25% of the entire animation each would look like:
[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];
In earlier iOS versions, you could queue up a series of animations a couple of ways, but I'd encourage you to avoid using a semaphore on the main thread.
One approach would be to wrap the animation in a concurrent NSOperation subclass, which doesn't complete until the animation does. You can then add your animations to your own custom serial queue:
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;
}]];
The AnimationOperation subclass might look like:
// AnimationOperation.h
#import <Foundation/Foundation.h>
#interface AnimationOperation : NSOperation
- (instancetype)initWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations;
#end
and
// 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
In my demonstration, above, I used a serial queue. But you could also use a concurrent queue, but use NSOperation dependencies to manage the relationship between the various animation operations. Lots of options here.
If you want to cancel the animations, you could then do something like the following:
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
You could also incorporate this into a custom cancel method in the operation, too, if you want.
You appear to be using a semaphore to block the main thread until animations compete. Unfortunately the main thread is the thread performing those animations so this will never occur.
You must not block the main thread of your application. By doing so you prevent any view drawing or responding to user input. You will also soon trigger an OS watchdog which detects your app as unresponsive and terminates it.
Animations an their completion blocks are expressed as asynchronous operations for good reason. Try to embrace that in your design.
Semaphore can solve all the block synchronization problems.
Two points
Need to create a serial queue.
dispatch_semaphore_wait and dispatch_semaphore_signal can not be in the same queue.
Here is a example
- (dispatch_queue_t)queue {
if (!_queue) {
_queue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
}
return _queue;
}
- (dispatch_semaphore_t)semaphore {
if (!_semaphore) {
_semaphore = dispatch_semaphore_create(0);
}
return _semaphore;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self funcA];
[self funcA];
[self funcA];
[self funcA];
[self funcA];
[self funcB];
}
- (void)funcA {
dispatch_async(self.queue, ^{
//Switch to main queue to perform animation
dispatch_async(dispatch_get_main_queue(), ^{
self.view.alpha = 1;
[UIView animateWithDuration:2 animations:^{
self.view.alpha = 0;
} completion:^(BOOL finished) {
NSLog(#"funcA completed");
//Unblock custom queue
dispatch_semaphore_signal(self.semaphore);
}];
});
//Block custom queue
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
});
}
- (void)funcB {
dispatch_async(self.queue, ^{
NSLog(#"funcB completed");
});
}
As Jonah said, there is no way to do that on the main thread. If you do not want to have nested blocks, there is nothing bad with it, but I understand your wish, simply put a method inside the block and the inner block then in the method. If you need closures in the inner block, you can pass them as an argument.
Doing so will enlarge your love to nested blocks. ;-)
As many people pointed out here, is true that the animation runs on the main thread and the semaphore usage stops the main thread. But this still can be done with a semaphore using this approach:
// create semaphore
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
// do animations
} completion:^(BOOL finished) {
// send signal
dispatch_semaphore_signal(semaphore);
}];
// create background execution to avoid blocking the main thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// wait for the semaphore
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// now create a main thread execution
dispatch_async(dispatch_get_main_queue(), ^{
// continue main thread logic
});
});

Reusing animation array blocks across views?

I've create a set of cool animation using labels on my first view.
I don't want to rewrite this code as I may improve this animation in the future.
However, I want to use this exact animation with different labels on another view / view controller. They will have the same name.
How would I do this, could someone suggest / provide an example ?
This is the animation array block code I based my code on...
http://xibxor.com/2013/03/27/uiview-animation-without-nested-hell/
NSMutableArray* animationBlocks = [NSMutableArray new];
typedef void(^animationBlock)(BOOL);
// getNextAnimation
// removes the first block in the queue and returns it
animationBlock (^getNextAnimation)() = ^{
animationBlock block = animationBlocks.count ? (animationBlock)[animationBlocks objectAtIndex:0] : nil;
if (block){
[animationBlocks removeObjectAtIndex:0];
return block;
}else{
return ^(BOOL finished){};
}
};
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
NSLog(#"Multi-step Animation Complete!");
}];
// execute the first block in the queue
getNextAnimation()(YES);
Here's an example of my code
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
lblLeft.transform = CGAffineTransformMakeScale(1.3,1.3);
lblMiddle.transform = CGAffineTransformMakeScale(1.3,1.3);
lblRight.transform = CGAffineTransformMakeScale(1.3,1.3);
} completion: getNextAnimation()];
}];
//add a block to our queue
[animationBlocks addObject:^(BOOL finished){;
[UIView animateWithDuration:1.0 animations:^{
//...animation code...
lblLeft.transform = CGAffineTransformIdentity;
lblMiddle.transform = CGAffineTransformIdentity;
lblRight.transform = CGAffineTransformIdentity;
} completion: getNextAnimation()];
}];
I have these three labels on different views within different view controllers.
Have you tried wrapping these in an object with class methods so that would keep your animation methods inside the object but pass the view to the wrapper methods? For example:
This method lives in class FooAnimationUtilities:
+ (void)animateViewWithScale:(UIView *)myView {
[animationBlocks addObject:^(BOOL finished){;
[myView animateWithDuration:1.0 animations:^{
//...animation code...
lblLeft.transform = CGAffineTransformMakeScale(1.3,1.3);
lblMiddle.transform = CGAffineTransformMakeScale(1.3,1.3);
lblRight.transform = CGAffineTransformMakeScale(1.3,1.3);
} completion: getNextAnimation()];
}];
}
Then from your other classes, that want to use this class...
In the .m above your implementation in your various view classes:
#import "FooAnimationUtilities.h"
And inside the view class methods (say animateMe) that need animation:
-(void)animateMe {
[FooAnimationUtilities animateViewWithScale:self];
}
So, in terms of passing in the labels, you could look at amending the class method to take (UILabel*)lblLeft or you could be a bit cleaner about it and pass over an array or a dict containing the label objects. You can even pass over the scale. So the class method name would be something like:
+ (void)animateView:(UIView *)myView andLabels:(NSArray *)labels withScale:(float)scale
You can use Categories. Categories are used to extend functions of existing classes. Here's the documentation on Categories: Link
If your code doesn't rely on a UIController being your "self", you can put that code in an NSObject and create an instance of it, or have a static instance of it when you need the animation. So you can just called [ObjectA animateMyAnimation];

The proper way of doing chain animations

void (^first_animation)();
void (^second_animation)(BOOL finished);
// First animation
first_animation = ^()
{
g_pin_info_screen.view.alpha = 1.0;
};
// Second animation
second_animation = ^(BOOL finished)
{
g_shadow_layer.opacity = 0.0;
void (^set_opacity_to_1)();
set_opacity_to_1 = ^()
{
g_shadow_layer.opacity = 1.0;
};
[UIView animateWithDuration : 2.0
delay : 0.0
options : UIViewAnimationCurveEaseInOut
animations : set_opacity_to_1
completion : nil
];
};
// Begin the animations
{
float duration;
duration = 0.35;
[UIView animateWithDuration : duration
delay : 0.00
options : UIViewAnimationCurveEaseInOut
animations : first_animation
completion : second_animation
];
}
First animation executes as expected. But second animation completes but without any animation.
Hope somebody could comment on whether the above scheme is the proper way of doing this or not.
__block NSMutableArray* animationBlocks = [NSMutableArray new];
typedef void(^animationBlock)(BOOL);
// getNextAnimation
// removes the first block in the queue and returns it
animationBlock (^getNextAnimation)() = ^{
if ([animationBlocks count] > 0){
animationBlock block = (animationBlock)[animationBlocks objectAtIndex:0];
[animationBlocks removeObjectAtIndex:0];
return block;
} else {
return ^(BOOL finished){
animationBlocks = nil;
};
}
};
[animationBlocks addObject:^(BOOL finished){
[UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//my first set of animations
} completion: getNextAnimation()];
}];
[animationBlocks addObject:^(BOOL finished){
[UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//second set of animations
} completion: getNextAnimation()];
}];
[animationBlocks addObject:^(BOOL finished){
[UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//third set
} completion: getNextAnimation()];
}];
[animationBlocks addObject:^(BOOL finished){
[UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//last set of animations
} completion:getNextAnimation()];
}];
// execute the first block in the queue
getNextAnimation()(YES);
With the help of the third party library there is a solution that looks like as below:
First, for convenience, define a category for UIView like so:
+(RXPromise*) rx_animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations
{
RXPromise* promise = [RXPromise new];
[UIView animateWithDuration:duration animations:animations: ^(BOOL finished){
// ignore param finished here
[promise fulfillWithValue:#"finished"]; // return just a string indicating success
}];
return promise;
}
Then, define any number of asynchronous animations which execute one after the other, as follows:
[UIView rx_animateWithDuration:duration animation:^{
... //define first animation
}]
.then(^id(id result){
// ignore result, it contains the fulfill value of the promise, which is #"finished"
return [UIView rx_animateWithDuration:duration animation:^{
... // define second animation
}];
}, nil)
.then(^id(id result){
return [UIView rx_animateWithDuration:duration animation:^{
... // define third animation
}];
}, nil)
.then(^id(id result){
return [UIView rx_animateWithDuration:duration animation:^{
... // and so force
};
}, nil);
The above statement is asynchronous!
With one line additional code you can achieve cancellation:
RXPromise* rootPromise = [UIView rx_animateWithDuration:duration animation:^{
... //define first animation
}];
rootPromise.then(^id(id result){
return [UIView rx_animateWithDuration:duration animation:^{
... // define second animation
}];
}, nil)
.then(^id(id result){
return [UIView rx_animateWithDuration:duration animation:^{
... // define third animation
}];
}, nil)
...
// later, in case you need to cancel pending animations:
[rootPromise cancel];
"RXPromise" library is available on GitHub: RXPromise. It's specifically designed for these use cases, and more. Due to full disclosure: I'm the author ;)
Just check here:
https://gist.github.com/vadimsmirnovnsk/bce345ab81a1cea25a38
You can chain it in functional style:
dispatch_block_t animationsBlock = ^{
[self.view updateConstraintsIfNeeded];
[self.view layoutIfNeeded];
};
[[[[[[[[[BARAnimation construct]
initially:animationsBlock]
animationWithDuration:0.425 animationConditions:^{
[gridView mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(imageView).with.offset(32.0);
}];
} animations:animationsBlock]
animationWithDuration:0.425 animationConditions:^{
[gridView mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(imageView).with.offset(0.0);
}];
} animations:animationsBlock]
animationWithDuration:0.425 animationConditions:^{
[gridView mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(imageView).with.offset(-32.0);
}];
} animations:animationsBlock]
animationWithDuration:0.425 animationConditions:^{
[gridView mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(imageView).with.offset(0.0);
}];
} animations:animationsBlock]
animationWithDuration:0.8 animationConditions:nil animations:^{
foreView.alpha = 1.0;
}]
finally:^{
[self.didEndSubject sendNext:[RACUnit defaultUnit]];
[self.didEndSubject sendCompleted];
}]
run];
You need to chain them together by using + (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
Within the options: argument, you need to include UIViewAnimationOptionBeginFromCurrentState
Good luck!
In the completion handler of the first animation, start the second one.

Resources