標籤:
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
源碼地址:https://github.com/rokistar/PassValueBetweenViewController
ios代理模式-(ViewControler之間傳值)