block是个好东西,是苹果官方推荐的一种方法,效率高,代码简单,今天用block主要是做一个简单传,暂时不对block详细介绍,关于__block的用法,后期会一一介绍;
接下来,通过一个block,将 SecondViewController 的数值传给 FirstViewController ;
FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()<UITextFieldDelegate>
{
//切换到下一个界面
UIButton *_btn;
//现实从 SecondViewController 传过来的值
UILabel *_label;
}
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor: [UIColor yellowColor]];
[self layouUI];
}
-(void)layouUI
{
// 创建lable
_label=[[UILabel alloc] initWithFrame:CGRectMake(100, 60, 120, 40)];
_label.backgroundColor=[UIColor whiteColor];
[self.view addSubview:_label];
//切换到 SecondViewController
_btn=[[UIButton alloc]initWithFrame:CGRectMake(100, 220, 120, 40)];
[_btn setBackgroundColor:[UIColor cyanColor]];
[_btn addTarget:self action:@selector(dobtn) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:_btn];
}
-(void)dobtn
{
SecondViewController *second=[[SecondViewController alloc]init];
second.mb=^(NSString *str){
_label.text=str;
};
[self.navigationController pushViewController:second animated:YES];
}
@end
创建第二个控制器:
SecondViewController.h
#import <UIKit/UIKit.h>
//定义block
typedef void(^Myblock)(NSString *str);
@interface SecondViewController : UIViewController
@property(strong,nonatomic)Myblock mb;
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
{
UIButton *_btn;
UILabel *_label;
UITextField *_textField;
}
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor purpleColor]];
[self layouUI];
}
-(void)layouUI
{
// 创建一个textfield
_textField=[[UITextField alloc]initWithFrame:CGRectMake(100, 140, 120, 40)];
_textField.borderStyle=UITextBorderStyleLine;
[self.view addSubview:_textField];
_btn=[[UIButton alloc]initWithFrame:CGRectMake(100, 220, 120, 40)];
[_btn setBackgroundColor:[UIColor cyanColor]];
[_btn addTarget:self action:@selector(dobtn) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:_btn];
}
-(void)dobtn
{
// 在这里调用block
self.mb(_textField.text);
[self.navigationController popViewControllerAnimated:YES];
}
@end
然后在 _textField 写入文字,例如写 welcome to air
如下图:
在第一个控制器上的label就会显示出来第二控制器上写的字符串;
如下图:
如果转载请注明转于:AirZilong的博客