眾所周知,block是iOS開發中一個經常使用的模塊, block 可以用來包含一段代碼塊,可以傳值, 用法靈活,但是也最讓很多開發者頭疼
今天說下block 作為參數傳遞的用法
- 1、 首先Block的書寫有些開發者會認為很繁瑣,其實不然
只要在代碼中敲擊 inline, 就會自動生產block
- 2、使用場景 : 假如我們想通過點擊一個按鈕來進入一段動畫,并且在動畫完畢時退出動畫,當然,也不是所有都要求 點擊按鈕進入動畫后就會退出動畫,有一些就不會
- 3、退出動畫的方法:
// 退出動畫
- (void)exit:(void (^)())task
{
self.view.userInteractionEnabled = NO;
// 動畫
for (int i = 0; i < 6; i++) {
// 動畫
POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionY];
anim.toValue = @(2 * CCJScreenW);
anim.springSpeed = 10;
anim.beginTime = CACurrentMediaTime() + [self.time[i] doubleValue];
[self.addbBtns[i] pop_addAnimation:anim forKey:nil];
}
POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionY];
anim.toValue = @(2 * CCJScreenW);
anim.springSpeed = 10;
anim.beginTime = CACurrentMediaTime() + [[self.time lastObject] doubleValue];
[self.imageView pop_addAnimation:anim forKey:nil];
// 動畫執行完調用
[anim setCompletionBlock:^(POPAnimation * anim, BOOL finish) {
[self dismissViewControllerAnimated:NO completion:nil];
// 如果有block參數,那么就調用參數的block代碼
if (task) {
task();
}
}];
}
首先
- (void)exit:(void (^)())task
就是退出動畫的方法, 而 task 也就是需要傳遞的block,此時在動畫完畢的方法里判斷并調用block
// 動畫執行完調用
[anim setCompletionBlock:^(POPAnimation * anim, BOOL finish) {
[self dismissViewControllerAnimated:NO completion:nil];
// 如果有block參數,那么就調用參數的block代碼
if (task) {
task();
}
}];
- 4、task參數的block的實現:
當然在block里不要忘記使用弱指針的self
// 當按鈕被點擊時調用
- (void)addBtnClick:(CJAddViewBtn *)addButton
{
__weak typeof(self) weakSelf = self;;
// 調用退出動畫的方法 給block 代碼傳遞具體的內容,^{ 是block的整體的內容,也就是說,這大括號內的整個都是參數,然后再exit中用task(又來調用了這些block 代碼)
[weakSelf exit:^{
NSUInteger index = [self.addbBtns indexOfObject:addButton];
switch (index) {
case 2:{
CJPostViewController *postView = [[CJPostViewController alloc] init];
[self.view.window.rootViewController presentViewController:[[CJNavigationController alloc] initWithRootViewController:postView] animated:YES completion:nil];
break;
}
default:
break;
}
}];
}
- 5、講解: 當點擊按鈕的時候,我們會進入
- (void)addBtnClick:(CJAddViewBtn *)addButton
這個方法
緊接著我們調用
[weakSelf exit:^{ ... }]
退出動畫的方法,就來到了一開始的
- (void)exit:(void (^)())task
的方法.這時^{ ... }之內的所有代碼將被作為block參數傳遞過去,也就是
方法中的task參數,那么在退出動畫的方法中,通過判斷task是否有值來決定是否調用這段block
這樣, 一段block代碼就成功被調用,里面的參數或者想要實現的功能就可以傳遞過去了