FirstViewController.h
#import <UIKit/UIKit.h>@interface FirstViewController : UIViewController@endFirstViewController.m
#import "FirstViewController.h"#import "SecondViewController.h"@interface FirstViewController ()<SecondViewControllerDelegate>/** 用于写入数据,最后该数据用于传递给第二个界面 */@property (weak, nonatomic) IBOutlet UITextField *first2Second;/** 用于显示第二个界面返回来时传递的数据 */@property (weak, nonatomic) IBOutlet UITextField *displayWithSecond;@end@implementation FirstViewController- (void)viewDidLoad {[super viewDidLoad];}#pragma mark - Navigation//点击传递按钮时会自动调用此方法- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {SecondViewController *vc = (SecondViewController *)segue.destinationViewController;if (self.first2Second.text.length > 0) {//将该界面中的数据传递给第二个界面vc.name = self.first2Second.text;}//设置当前控制器为SecondViewController控制器的代理vc.delegate = self;}#pragma mark - 实现SecondViewControllerDelegate中的协议方法-(void)secondViewControllerDidDit:(SecondViewController *)viewController andName:(NSString *)name{//将第二个界面中的数据返回给第一个界面(此界面)self.displayWithSecond.text = name;}@endSecondViewController.h
#import <UIKit/UIKit.h>@class SecondViewController;@protocol SecondViewControllerDelegate <NSObject>/** SecondViewControllerDelegate协议中的方法 */-(void)secondViewControllerDidDit:(SecondViewController *)viewController andName:(NSString *)name;@end@interface SecondViewController : UIViewController@property(nonatomic,strong) NSString *name;@property(nonatomic,weak) id<SecondViewControllerDelegate> delegate;@endSecondViewController.m
#import "SecondViewController.h"@interface SecondViewController ()/** 用于写入数据,最后将数据返回给第一个界面 */@property (weak, nonatomic) IBOutlet UITextField *second2First;/** 用于显示第一个界面传过来的数据 */@property (weak, nonatomic) IBOutlet UITextField *displayWithFirst;/** 点击此按钮,第二个控制器将弹出栈,界面将返回到第一个界面 */- (IBAction)second2First:(UIButton *)sender;@end@implementation SecondViewController- (void)viewDidLoad {[super viewDidLoad];//显示第一个界面传递过来的数据信息self.displayWithFirst.text = self.name;}//点击该按钮,数据将返回给第一个界面显示- (IBAction)second2First:(UIButton *)sender {if (self.second2First.text.length > 0) {//如果有实现该协议方法的控制器,则将数据传给该控制器if ([self.delegate respondsToSelector:@selector(secondViewControllerDidDit:andName:)]) {[self.delegate secondViewControllerDidDit:self andName:self.second2First.text];}}[self.navigationController popViewControllerAnimated:YES];}@end以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持脚本之家。