1.代理。
代理从后往前传值(比如nsstring)。
本文从B类(MyVC)传字符串到A类(ViewController)。
![](https://img.haomeiwen.com/i2127575/b3ac5ff7d5997131.png)
![](https://img.haomeiwen.com/i2127575/48361785746be582.png)
![](https://img.haomeiwen.com/i2127575/23dd78702284607b.png)
2.block。
本例为从B类TwoViewController向A类OneViewController传值。所以先从B类开始。
TwoViewController.h
//声明并描述block
#importtypedef void(^ChangeBgColorBlock)(NSInteger);
@interface TwoViewController : UIViewController
//属性描述block时,一定要用copy。
@property (nonatomic ,copy)ChangeBgColorBlock block;
@end
TwoViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"Two";
}
- (IBAction)btnClick:(UIButton *)btn
{
NSInteger index = (NSInteger)btn.tag;
// 执行(回调)block
_block(index);
[self.navigationController popViewControllerAnimated:YES];
}
OneViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"One";
}
- (IBAction)gotoNext:(id)sender
{
TwoViewController *vc = [[TwoViewController alloc] init];
// 定义了block,将来在TwoViewController的vc中,点击不同的按钮,就会回调block,执行下面block定义中switch case语句,改变当前view的bgColor。
vc.block = ^(NSInteger chuangjinlaideInt)
{
switch (chuangjinlaideInt)
{
case 1:
{
self.view.backgroundColor = [UIColor redColor];
}
break;
case 2:
{
self.view.backgroundColor = [UIColor greenColor];
}
break;
case 3:
{
self.view.backgroundColor = [UIColor blueColor];
}
break;
default:
break;
}
};
[self.navigationController pushViewController:vc animated:YES];
}
初学者,请大神绕道或指正。
网友评论