Block的示例学习
1 @interface ViewController () 2 3 4 @property (weak, nonatomic) IBOutlet UIButton *btn; 5 6 7 8 - (IBAction)reset:(id)sender; 9 - (IBAction)run:(id)sender; 10 - (IBAction)rotate:(id)sender; 11 - (IBAction)scale:(id)sender; 12 13 @end 14 15 @implementation ViewController 16 17 - (void)viewDidLoad { 18 [super viewDidLoad]; 19 20 21 } 22 23 //定义函数,参数是block类型 无返回值,无参数的block 24 25 - (void)btnClickWithBlock:(void (^)())block 26 { 27 // 0.动画(头部-开始动画) 28 [UIView beginAnimations:nil context:nil]; 29 // 设置动画的执行时间 30 [UIView setAnimationDuration:1.0]; 31 32 //block的调用 33 block(); 34 35 // 1.动画(尾部-提交动画-执行动画) 36 [UIView commitAnimations]; 37 } 38 39 40 41 - (void)didReceiveMemoryWarning { 42 [super didReceiveMemoryWarning]; 43 // Dispose of any resources that can be recreated. 44 } 45 46 47 //重置 48 - (IBAction)reset:(id)sender { 49 50 [self btnClickWithBlock:^{ 51 _btn.transform = CGAffineTransformIdentity; 52 }]; 53 } 54 55 56 57 //行走 58 - (IBAction)run:(id)sender { 59 60 [self btnClickWithBlock:^{ 61 62 NSLog(@"self = %@",self); //表示此控制器 63 64 // 1.先取出frame 65 CGPoint tempCenter = _btn.center; 66 67 // 2.取出按钮的tag标记 68 NSInteger tag = [sender tag]; 69 70 switch (tag) { 71 case 10: 72 73 tempCenter.y -= kDelta; 74 75 break; 76 77 case 20: 78 79 tempCenter.x -= kDelta; 80 break; 81 82 case 30: 83 84 tempCenter.y += kDelta; 85 break; 86 87 88 case 40: 89 90 tempCenter.x += kDelta; 91 break; 92 93 94 default: 95 break; 96 } 97 98 // 3.重新赋值按钮的frame 99 _btn.center = tempCenter; 100 101 102 103 }]; 104 } 105 106 //旋转 107 - (IBAction)rotate:(id)sender { 108 109 [self btnClickWithBlock:^{ 110 NSInteger tag = [sender tag]; 111 if (10 == tag) { // 左 112 _btn.transform = CGAffineTransformRotate(_btn.transform, M_PI_4 * -1); 113 } else { // 右 114 _btn.transform = CGAffineTransformRotate(_btn.transform, M_PI_4 * 1); 115 } 116 }]; 117 118 } 119 120 //缩放 121 - (IBAction)scale:(id)sender { 122 123 [self btnClickWithBlock:^{ 124 CGFloat scale = [sender tag] == 20 ? 1.2 : 0.8; 125 _btn.transform = CGAffineTransformScale(_btn.transform, scale, scale); 126 }]; 127 128 129 }