摘要:这里我们有两个ViewController,即MyFirstViewController和MySecondViewController,通过点击MyFirstViewController中按钮跳转至MySecondViewController页面中,然后在需要返回的地方将值传回至MyFirstViewController中。
MyFirstViewControll | MySecondViewController |
MySecondViewController.h
#import <UIKit/UIKit.h>
@class MySecondViewController;
//1. 定义委托协议
@protocol MySecondViewDelegate <NSObject>
-(void)secondViewController:(MySecondViewController*)secondVC
message:(NSString *)message;
@end
@interface MySecondViewController : UIViewController
//2. 定义delegate属性
@property (nonatomic, weak)id<MySecondViewDelegate> delegate;
@end
MySecondViewController.m
#import "MySecondViewController.h"
@interface MySecondViewController ()
@property (weak, nonatomic) IBOutlet UITextField *mesTextField;
@end
@implementation MySecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)goBackBtn:(id)sender {
//3. 给delegate发消息,传参数
[self.delegate secondViewController:self
message:self.mesTextField.text];
[self dismissViewControllerAnimated:YES completion:nil];}
@end
MyFirstViewControll.h
#import <UIKit/UIKit.h>
@interface MyFirstViewController : UIViewController
@end
MyFirstViewControll.m
#import "MyFirstViewController.h"
#import "MySecondViewController.h"
//1.遵守协议
@interface MyFirstViewController () <MySecondViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *getInfoLabel;
@end
@implementation MyFirstViewController
//2. 实现协议中的方法
- (void)secondViewController:(MySecondViewController *)secondVC message:(NSString *)message
{
self.getInfoLabel.text = message;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)skipBtn:(id)sender {
MySecondViewController *secondVC = [[MySecondViewController alloc]initWithNibName:@"MySecondViewController" bundle:nil];
//3. 将自己设置成为委托方的delegate
secondVC.delegate = self;
[self presentViewController:secondVC animated:YES completion:nil];
}
@end