多个ViewController进行传值,有三种方式:
1:使用代理
2: 使用Block
3:使用单例
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title=@"title1";
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(next)];
}
-(void)next
{
AZSecondViewController *secondVC=[[AZSecondViewController alloc] init];
secondVC.title=@"title2";
//第一种:使用代理 ,在secondVC中见代码
secondVC.delegate=self;
//第二种:使用BLOCK
//定义secondVC中blockFun
secondVC.blockFun=^(NSString *title)
{
self.navigationItem.title=title;
};
//第三种:使用单例 -(void)viewWillAppear:(BOOL)animated
[self.navigationController pushViewController:secondVC animated:YES];
}
//第三种:使用单例
-(void)viewWillAppear:(BOOL)animated
{
AZSingleton *sington=[AZSingleton shareSingleton];
if (sington.str==nil) {
return;
}
self.navigationItem.title=sington.str;
}
//实现协议中的方法
-(void)getVaule:(NSString *)title
{
self.navigationItem.title=title;
}
UISecondViewController:
//创建三个按键
UIButton *btn1=[UIButton buttonWithType:UIButtonTypeCustom];
btn1.frame=CGRectMake(10, 60, 300, 20);
[btn1 setTitle:@"使用代理" forState:UIControlStateNormal];
btn1.tag=10;
[btn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
UIButton *btn2=[UIButton buttonWithType:UIButtonTypeCustom];
btn2.frame=CGRectMake(10, 90, 300, 20);
btn2.tag=11;
[btn2 setTitle:@"使用block" forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2];
UIButton *btn3=[UIButton buttonWithType:UIButtonTypeCustom];
btn3.frame=CGRectMake(10, 120, 300, 20);
btn3.tag=12;
[btn3 setTitle:@"使用单例" forState:UIControlStateNormal];
[btn3 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn3];
}
-(void)btnClick:(UIButton *)btn
{
if (btn.tag==10) {
[self.delegate getVaule:@"使用代理"];
}
if (btn.tag==11) {
self.blockFun(@"使用block");//定义了一个快函数,这里只是调用一下块函数,实现在rootVC中。
}
if (btn.tag==12) {
AZSingleton *singleton=[AZSingleton shareSingleton];
singleton.str=@"使用单例";
}
}
效果: