在Object/C编程语言中,有许多地方用到了block代码块进行操作,例如:UIView的动画模块、地图的定点查询等。block是一种C语言风格的代码模式,它能为我们解决一些复杂问题提供一种简便方法,所以block也是iOS推荐使用的一种代码模式。
在代码重构的过程中,我们可以使用block来对代码进行重构:
- (void)btnClickBlock:(void(^)())block
{[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
block();
[UIView commitAnimations];
}
- (void)onButtonTapped:(UIButton *)sender
{
UIView *view1 = [self.window viewWithTag:101];
UIView *view2 = [self.window viewWithTag:102];
UIView *view3 = [self.window viewWithTag:103];
// [UIView beginAnimations:nil context:nil];
// [UIView setAnimationDuration:1.0];
[self btnClickBlock:^{
CGRect frame = view1.frame;
view1.frame = view2.frame;
view2.frame = view3.frame;
view3.frame = frame;
}];
// [UIView commitAnimations];
}
带参数的 block
- (void)btnClick:(UIButton *)sender block:(void(^)())block
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
block();
[UIView commitAnimations];
}
- (void)onButtonTapped:(UIButton *)sender
{
UIView *view1 = [self.window viewWithTag:101];
UIView *view2 = [self.window viewWithTag:102];
UIView *view3 = [self.window viewWithTag:103];
// [UIView beginAnimations:nil context:nil];
// [UIView setAnimationDuration:1.0];
[self btnClickBlock:^{
CGRect frame = view1.frame;
view1.frame = view2.frame;
view2.frame = view3.frame;
view3.frame = frame;
}];
// [UIView commitAnimations];
}