到目前为止,有4中传值方法
1.属性传值
2.代理传值
3.单例 传值
4.block传值
block传值,是在一个类A里面,把block设定为属性,在另一个类B中包含这个类。在B中创建一个A的对象,使用block。这里是block的实现。
在A类里面创建一个B对象,使用block。这里是block的调用。
A类为RootViewController,B类为FirstViewController.
把A类中的按钮的颜色传到B类中
RootViewController.h
#import <UIKit/UIKit.h>
//将void(^)(UIColor *)重名为BLOCK
typedef void(^BLOCK)(UIColor *);
@interface RootViewController : UIViewController
//①.将block声明为属性,因为其他页面会用的到
@property(nonatomic,copy)BLOCK block;
@end
RootViewController.m
#import "RootViewController.h"
#import "FirstViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
#pragma mark --------------创建rightBarButtonItem
[self createBarButtonItems];
[self createButton];
// Do any additional setup after loading the view.
}
-(void)createButton{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor redColor];
button.frame = CGRectMake(100, 100, 60, 40);
[button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
-(void)didClickButton:(UIButton *)button{
FirstViewController *firstVC = [[FirstViewController alloc]init];
[self.navigationController pushViewController:firstVC animated:YES];
//当点击button按钮的时候,调用block,调用的形式:block变量名(实参列表)
[firstVC view];
_block(button.backgroundColor);
[firstVC release];
}
-(void)createBarButtonItems{
UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"PUSH" style:UIBarButtonItemStylePlain target:self action:@selector(clickToPush:)];
self.navigationItem.rightBarButtonItem= rightButtonItem;
}
-(void)clickToPush:(UIBarButtonItem *)button{
///推出下一级页面
FirstViewController *firstVC = [[FirstViewController alloc]init];
[self.navigationController pushViewController:firstVC animated:YES];
}
FirstViewController.m中的代码,.h中基本没有代码,所以就不列举了
#import "FirstViewController.h"
#import "RootViewController.h"
typedef int(^Block)(int ,int );
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor];
self.view.backgroundColor = _block;
//匿名函数
// int (int a ,int b);
// int (int a ,int b){
//
// return a + b;
//
// }
//定义block变量 , 分三部分
//1. 类型 : int (^)(int , int )
//2.变量名:block
//3.初值:^(int a,int b){ return a + b; };
Block block = ^int (int a,int b){
return a+b;
};
//二,如何使用block 形式:block变量名(实参列表)
int a = block(3, 5);
NSLog(@"%d",a);
//使用block实现对两个整数求积
Block mutiBlock = ^int (int a ,int b){
return a*b;
};
int b = mutiBlock(3,5);
NSLog(@"%d",b);
//获得上一个页面对应的视图控制器对象
RootViewController *controller =(RootViewController *)self.navigationController.viewControllers[0];
controller.block = ^void(UIColor *color){
self.view.backgroundColor = color;
};