开发者

What should I pass as a parameter?

开发者 https://www.devze.com 2023-03-15 18:10 出处:网络
The UIView class has a class method: + (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnima开发者_C百科tionOptions)options animations:(void (^)(void))animati

The UIView class has a class method:

+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnima开发者_C百科tionOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion

It's the first time I've seen an argument like the animation and completion arguments. What do I write in this place:animations:(void (^)(void))animations ? What does (^) and void mean?


The ^ character denotes a c block. Blocks are code chunks that get executed whenever function requires it. I'm not sure about animations: parameter, but completion: block gets executed (as name states) when animation ends.

The possible call could look like this:

[UIView transitionWithView:myView 
                  duration:1.0 
                   options:0 
                animations:^{} /* this denotes empty block */
                completion:^{ 
                                NSLog(@"Animation has completed");
                           }
];


What your are seeing there is Objective-C's block syntax. The syntax is completely obtuse, frustrating, and mind-numbing, but what it is doing is actually very simple.

A block is logically equivalent to a closure in other languages such as JavaScript, so ignoring the nasty syntax you can think of the signature being something along the lines of:

function transitionWithView(view, duration, options, animationFunction, onComplete);

...where animationFunction and onComplete are closures (or blocks, to use the Objective-C parlance). Basically you can think of them as function pointers that preserve the state of the context in which they are created.

Anyhow, the (^) token in Objective-C simply denotes a block. The type that precedes it denotes the return-type of the block (so void in your example, meaning that neither block returns a value), and the types that follow it in parenthesis denote any arguments that the block takes (so none for animations, and a BOOL called 'finished' for the completion block.

0

精彩评论

暂无评论...
验证码 换一张
取 消