首页 > 代码库 > block传值
block传值
定义block和定义delegate一样,都是在得到需要的值那个页面的类里定义。
eg:A类、B类,我要将A类中的值传给B类,那么我就到A类中定义block,B类取值就可以了。。。。
For example:
第一步:
A类中:
.h文件:
#import "BaseViewController.h"
//定义块
typedef void (^addCommunity)(UIImage *img,NSString *title);
@interface MoreViewController : BaseViewController
@property(nonatomic,copy)addCommunity adds;
-(void)addCommunityWithBlock:(addCommunity)addBlock;
.m文件:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
imgView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
NSString *img = @"market-android.png";
imgView.image = [UIImage imageNamed:img];
[self.view addSubview:imgView];
lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(135, 230, 100, 30)];
lblTitle.text = @"标题";
lblTitle.textColor = [UIColor redColor];
[self.view addSubview:lblTitle];
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 300, 100, 30)];
[btn setTitle:@"添加" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
[btn setBackgroundColor:[UIColor redColor]];
[self.view addSubview:btn];
}
-(void)add{
_adds(imgView.image,lblTitle.text); //block传值
[self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)addCommunityWithBlock:(addCommunity)addBlock{
_adds = addBlock;
}
第二步:
B类中:
.m文件:
[more addCommunityWithBlock:^(UIImage *img,NSString *title){
NSDictionary *dic = [NSDictionary dictionaryWithObject:img forKey:title];
}];
在你需要用到值的地方,调用block,说明:more是A类的一个别名。这样就把B页面的值传到了A页面的NSDictionary中。。。。。。。我觉得写得还算清楚吧!嘿嘿......