您的位置:首页 > 其它

Block--两个界面 间回调传值

2016-01-13 14:30 274 查看
使用Block的地方很多,其中传值只是其中的一小部分,下面介绍Block在两个界面之间的传值:

首先,创建两个视图控制器,在第一个视图控制器中创建一个UILabel和一个UIButton,其中UILabel是为了显示第二个视图控制器传过来的字符串,UIButton是为了push到第二个界面。

第二个视图控制器

#import <UIKit/UIKit.h>

typedef void (^PassValueBlock) (NSString *ShowText);
@interface DetailViewController : UIViewController

@property (nonatomic,copy) PassValueBlock ShowTextBlock;

-(void)ShowTextValue:(PassValueBlock)block;

@end


#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor=[UIColor blueColor];
button.frame=CGRectMake(100, 100, 100, 20);
[button setTitle:@"回调传值" forState:UIControlStateNormal];
[button addTarget:self action:@selector(PassValue:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}

-(void)PassValue:(UIButton *)sender{

[self.navigationController popViewControllerAnimated:YES];
//block 传值
if (self.ShowTextBlock != nil) {
self.ShowTextBlock(@"20");
}
}

-(void)ShowTextValue:(PassValueBlock)block{
//保存block
self.ShowTextBlock = block;
}


第一个视图控制器

#import "RootViewController.h"
#import "DetailViewController.h"
@interface RootViewController ()
@property (nonatomic,strong) UILabel *label;
@end

@implementation RootViewController

- (void)viewDidLoad {
[super viewDidLoad];
//创建显示数据的label
self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 300, 40, 60)];
self.label.backgroundColor = [UIColor grayColor];

[self.view addSubview:self.label];

//创建button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor blueColor];
button.frame = CGRectMake(100, 100, 40, 20);
[button addTarget:self action:@selector(Push:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}

-(void)Push:(UIButton *)sender{
//跳转控制器
DetailViewController *detailVC = [[DetailViewController alloc] init];
[self.navigationController pushViewController:detailVC animated:YES];
//回调传值
[detailVC ShowTextValue:^(NSString *ShowText) {
self.label.text = ShowText;
}];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  界面 传值-Block