第一种(属性传值)
正传是利用属性传值(例如,把第一个页面中TextFiled中的text传到第二个页面中的一个TextField的text中)
在第一个页面
ViewControllerFirst.h
@property UITextField *accounttextField;
ViewControllerFirst.m中
//一个Button的点击事件,跳转到第二个界面
-(void) pressToSecondViewController {
SecondViewController *secondViewController = [[SecondViewController alloc] init];
//用第二个页面中的NString *str属性进行接收
registerViewController.str = _accounttextField.text;
//跳转到第二个界面
[self presentViewController:registerViewController animated:YES completion:nil];
}
SecondViewController.h中
@property NSString *str; //用于接收
@property UITextField *accoutTextField;
在SecondViewController.m中
_accoutTextField.text = _str; //进行赋值操作,将接收到的赋值给 _accoutTextField.text
第二种 (协议传值)
(例如,将一个Account类,从SecondViewController传到ViewControllerFirst)
首先定义一个类Account,并且设置代理
#import <Foundation/Foundation.h>
@class Account;
NS_ASSUME_NONNULL_BEGIN
//设置代理
@protocol ZWYDelegate <NSObject>
//方法,传输account
-(void)pass:(Account *) account;
@end
@interface Account : NSObject
@property NSString *userNameString;
@property NSString *passWordString;
@end
NS_ASSUME_NONNULL_END码片
然后在ViewControllerFirst中,遵守协议方法
#import <UIKit/UIKit.h>
#import "Account.h"
@interface ViewController : UIViewController <UITextFieldDelegate, ZWYDelegate>
@property NSMutableArray *accountArray;
在ViewControllerFirst.m中实现协议中的方法
//一个Button的点击事件,跳转到第二个界面
-(void) pressToSecondViewController {
SecondViewController *secondViewController = [[SecondViewController alloc] init];
//设置第二个界面的ZWYDelegate为第一个窗口的self
secondViewController.zwyDelegate = self;
[self presentViewController:registerViewController animated:YES completion:nil];
}
//实现协议函数 这里是把,第二个页面中的account传回来,加入到一个数组当中
- (void)pass:(Account *)account {
[_accountArray addObject:account];
}
在SecondViewController.h中
//用weak是防止循环引用
@property (nonatomic, weak)NSObject <ZWYDelegate> *zwyDelegate;
在SecondViewController.m 中
//在返回第一个页面的时候
-(void)back {
[self dismissViewControllerAnimated:YES completion:nil];
//respondsToSelector是判断pass方法是否已经实现,如果实现进行传值操作
if([self.zwyDelegate respondsToSelector:@selector(pass:)]) {
//通过委托协议传值
[self.zwyDelegate pass:_accountAccount];
}
}