iOS传值-delegate
目的:使用delegate在两个ViewController之间传值
1,新建Single View Application工程,新建SecondViewController
2,在SecondViewController中设置代理
#import <UIKit/UIKit.h> @protocol secondViewControllerDelegate <NSObject> - (NSString *)value; @end @interface SecondViewController : UIViewController @property (nonatomic,assign) id <secondViewControllerDelegate> delegate; @end
3,在ViewController中添加UIButton,绑定事件,用于跳转到SecondViewController,在ViewController中添加UITextField,用于输入需要传递的值
4,在ViewController中添加代理协议,设置SecondViewController的代理为ViewController,实现代理方法
代码如下:
#import "ViewController.h" #import "SecondViewController.h" @interface ViewController () <secondViewControllerDelegate>{ UITextField *_textField; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //添加按钮 UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 200, 300, 40)]; btn.backgroundColor = [UIColor grayColor]; [btn setTitle:@"ToSecondViewController" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(toSecondViewController) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; //添加textField _textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 300, 40)]; _textField.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_textField]; } - (void)toSecondViewController { SecondViewController *second = [[SecondViewController alloc] init]; //设置SecondViewController的代理为ViewController自己 second.delegate = self; [self presentViewController:second animated:YES completion:nil]; }
//实现代理方法
-(NSString *)value { return _textField.text; } @end
5,在SecondViewController中添加UIButton,绑定事件,用于返回到ViewController
6,在SecondViewController中添加UILabel,用于显示传递的值
代码如下:
#import "SecondViewController.h" @interface SecondViewController () @end @implementation SecondViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; // 添加label用于显示传递的值 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 300, 40)]; label.text = [_delegate value]; label.backgroundColor = [UIColor greenColor]; [self.view addSubview:label]; //添加按钮 UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 200, 300, 40)]; btn.backgroundColor = [UIColor blueColor]; [btn setTitle:@"ToViewController" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(backFirstViewController) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } - (void)backFirstViewController { [self dismissViewControllerAnimated:YES completion:nil]; } @end