两个ViewController间传值(二)

网友投稿 297 2022-08-24

两个ViewController间传值(二)

在上一篇 ​​两个ViewController间传值(一)​​中说明了如何从A传值到B,这次要讲的是如何从A进入B,在B输入值后回传给A,这类似于Android中的利用Activity的onActivityResult回调方法实现两个Activity之间的值传递,那么在IOS中如何实现这个功能呢,答案是使用Delegate(委托协议)。

首先来看看工程结构图:

其中有两个ViewController分别对应两个界面,一个协议PassValueDelegate用来实现传值协议,UserEntity是传递数据的对象。

下面说明关键代码,完整代码在后面有下载链接。

[cpp]  ​​view plain​​​ ​​copy​​

#import @class UserEntity;@protocol PassValueDelegate -(void)passValue:(UserEntity *)value;@end

在第一个窗口实现协议:

[cpp]  ​​view plain​​​ ​​copy​​

#import #import "PassValueDelegate.h"//第一个窗口遵守PassValueDelegate@interface ViewController : UIViewController@property (retain, nonatomic) IBOutlet UILabel *nameLabel;@property (retain, nonatomic) IBOutlet UILabel *ageLabel;@property (retain, nonatomic) IBOutlet UILabel *gendarLabel;- (IBAction)openBtnClicked:(id)sender;@end

.m文件中实现协议的方法:

[cpp]  ​​view plain​​​ ​​copy​​

//实现协议,在第一个窗口显示在第二个窗口输入的值,类似Android中的onActivityResult方法-(void)passValue:(UserEntity *)value{self.nameLabel.text = value.userName;"%d",value.age];self.gendarLabel.text = value.gendar;}

[cpp]  ​​view plain​​​ ​​copy​​

[cpp]  ​​view plain​​​ ​​copy​​

#import #import "PassValueDelegate.h"@interface SecondViewController : UIViewController@property (retain, nonatomic) IBOutlet UITextField *nameTextField;@property (retain, nonatomic) IBOutlet UITextField *ageTextFiled;@property (retain, nonatomic) IBOutlet UITextField *gendarTextField;//这里用assign而不用retain是为了防止引起循环引用。@property(nonatomic,assign) NSObject *delegate;- (IBAction)okBtnClicked:(id)sender;- (IBAction)closeKeyboard:(id)sender;@end

[cpp]  ​​view plain​​​ ​​copy​​

- (IBAction)okBtnClicked:(id)sender {UserEntity *userEntity = [[UserEntity alloc] init];userEntity.userName = self.nameTextField.text;userEntity.gendar = self.gendarTextField.text;userEntity.age = [self.ageTextFiled.text intValue];//通过委托协议传值[self.delegate passValue:userEntity];//退回到第一个窗口[self.navigationController popViewControllerAnimated:YES];[userEntity release];}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:打造超大暖心笑脸,名创优品这次营销太美好!(名创优品营销策略)
下一篇:IOS谓词--NSPredicate
相关文章

 发表评论

暂时没有评论,来抢沙发吧~