Jake Gearhart
Jake Gearhart

Reputation: 307

Separate function for UIView animateWithDuration animations and completion parameters

I am working with animations in iOS7 with objective-c. I am trying to use the animateWithDuration function which has the following definition:

[UIView animateWithDuration:(NSTimeInterval) animations:^(void)animations completion:^(BOOL finished)completion]

I can use this just fine, but it makes my code overly long because I have to put my animation and completion functions all in this declaration. I would like to create a separate function and pass it into the animation function call.

Specifically I would like to be able to have a separate completion function to use with multiple animations, which would also require the ability to pass it the parameter of a the specific view's id.

Could someone explain how to set up a function that can be passed into the animate function, and also what the '^' in the ^(void) and ^(BOOL) means?

Thanks

Upvotes: 0

Views: 590

Answers (2)

michaelsnowden
michaelsnowden

Reputation: 6202

Don't overcomplicate things. Just use this method instead:

[UIView animateWithDuration:1.0 animations:^{
    // your animations
}];

Next time you come across a block you have no use for, just put nil in the block.

[UIView animateWithDuration:1.0
                     animations:^{
                         // your animations
                     }
                     completion:nil];

The ^ means that you are declaring a block in Objective-C.

If you just want to make your method call shorter, you can do this:

void (^myCompletionBlock)(BOOL finished) = ^void(BOOL finished) {
    // What you want to do on completion
};

[UIView animateWithDuration:1.0
                 animations:^{
                     // your animations
                 }
                 completion:myCompletionBlock];

Upvotes: 0

colinbrash
colinbrash

Reputation: 481

That ^ indicates a block (note that these are not functions). You can certainly do what you want. You would use:

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

So your code would look something like this:

void (^animations)() = ^{
    // Do some animations.
};

void (^completion)(BOOL) = ^(BOOL finished){
    // Complete.
};

[UIView animateWithDuration:1 animations:animations completion:completion];

FYI, this is a great reference for block syntax: http://goshdarnblocksyntax.com/

Upvotes: 0

Related Questions