根视图:
#import "RootViewController.h"
#import "ModalViewController.h"
@interface RootViewController() {
ModalViewController *modal;
}
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1) 设置背景颜色
self.view.backgroundColor = [UIColor cyanColor];
//2) 设置一个Label
//a) 创建一个Label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25, 100, 270, 30)];
//b) 设置该label的tag
label.tag = 1000;
//c) 设置label的内容
label.text = @"Block的传值";
//d) 设置背景颜色
label.backgroundColor = [UIColor orangeColor];
//e) 设置字体颜色
label.textColor = [UIColor whiteColor];
//f) 设置居中方式
label.textAlignment = NSTextAlignmentCenter;
//g) 添加label
[self.view addSubview:label];
//3) 设置跳转的button
//a) 创建button
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//b) 设置其frame
button.frame = CGRectMake(0, 0, 200, 30);
//c) 设置其在屏幕的中心
button.center = self.view.center;
//d) 设置背景颜色
button.backgroundColor = [UIColor lightGrayColor];
//e) 设置显示的内容
[button setTitle:@"跳转" forState:UIControlStateNormal];
//f) 设置相应事件
[button addTarget:self
action:@selector(buttonAction:)
forControlEvents:UIControlEventTouchUpInside];
//g) 添加到页面上
[self.view addSubview:button];
//4) 初始化modal
modal = [[ModalViewController alloc]init];
}
#pragma mark - button的响应事件
-(void)buttonAction:(UIButton *)button{
// 防止内存泄漏
__weak RootViewController *root = self;
// 用block传值
modal.block = ^(NSString *text){
UILabel *label = (UILabel *)[root.view viewWithTag:1000];
label.text = text;
};
// 控制器的跳转
[self presentViewController:modal animated:YES completion:nil];
}
跳转视图:
#import "ModalViewController.h"
@implementation ModalViewController
-(void)viewDidLoad{
[super viewDidLoad];
//1) 设置背景颜色
self.view.backgroundColor = [UIColor orangeColor];
//2) 设置一个TextField
//a) 创建一个TextField
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(25, 100, 270, 30)];
//b) 设置tag
textField.tag = 2000;
//c) 设置显示的效果
textField.borderStyle = UITextBorderStyleRoundedRect;
//d) 显示提示语
textField.placeholder = @"请输入一段文字...";
//e) 添加到self.view上
[self.view addSubview:textField];
//3) 设置跳转你的button
//a) 创建button
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//b) 设置其frame
button.frame = CGRectMake(0, 0, 200, 30);
//c) 设置其在屏幕的中心
button.center = self.view.center;
//d) 设置背景颜色
button.backgroundColor = [UIColor lightGrayColor];
//e) 设置显示的内容
[button setTitle:@"返 回" forState:UIControlStateNormal];
//f) 设置相应事件
[button addTarget:self
action:@selector(backAction:)
forControlEvents:UIControlEventTouchUpInside];
//g) 添加到页面上
[self.view addSubview:button];
}
#pragma mark - 按钮的响应事件
-(void)backAction:(UIButton *)button{
// 获取当前输入框
UITextField *textFiled = (UITextField *)[self.view viewWithTag:2000];
// 给block传值
if (self.block != nil) {
self.block(textFiled.text);
}
// 关闭视图
[self dismissViewControllerAnimated:YES completion:nil];
}