iOS学习_界面通讯

属性传值(从前往后传)

第一步:在你想传过去的那个界面的.h文件中声明属性,用来接收上一个界面传过来的内容

1 #import <UIKit/UIKit.h>
2 
3 @interface SecondViewController : UIViewController
4 
5 // 第一步: 声明属性,用来存放上一页传过来的数据
6 @property (nonatomic, copy) NSString *textString;
7 
8 
9 @end

第二步:把你想传的内容赋给第一步声明的属性,一定要在push之前

 1 // 实现点击事件
 2 - (void)loginButtonClick:(UIButton *)sender {
 3     
 4     // 创建控制器对象
 5     SecondViewController *secondVC = [[SecondViewController alloc] init];
 6     
 7     // 第二步:进行赋值
 8     secondVC.textString = self.rootView.userTextField.text;
 9     
10     
11     // 导航控制器push栈中
12     [self.navigationController pushViewController:secondVC animated:YES];
13     
14 }

第三步:把属性接收过来的内容显示出来

 1 // 第三步: 显示内容 2 self.nameLabel.text = self.textString; 

代理传值(从后往前传)

前三步是在传内容的界面完成的

第一步:定义协议

1 // 第一步:定义协议
2 @protocol SecondViewControllerDelegate <NSObject>
3 
4 // 声明协议方法 用来传值,要传什么类型的值参数就是什么类型
5 - (void)passValueWithString:(NSString *)textString;
6 
7 @end

第二步:声明代理属性

1 @interface SecondViewController : UIViewController
2 
3 // 第二步:声明代理属性
4 
5 // 代理的语义设置使用assign ,防止循环引用
6 @property (nonatomic, assign) id <SecondViewControllerDelegate>delegate;
7 
8 
9 @end

第三步:使用代理调用代理的传值方法

 1 // 实现方法(使用代理从后往前传值)
 2 - (void)submitButtonClick:(UIButton *)sender {
 3     
 4     // 1.把输入的内容传到第一页
 5     
 6     // 第三步:使用代理调用代理的传值方法
 7     [self.delegate passValueWithString:self.eatTextField.text];
 8    
 9     
10     // 2.跳回到第一页
11     [self.navigationController popViewControllerAnimated:YES];
12 }
13 
14 @end

后三步是在接收内容的界面完成的

第四步:遵守协议

 1 // 第四步:遵守协议 2

@interface RootViewController ()<SecondViewControllerDelegate> 

第五步:设置代理

 1 // 实现事件
 2 - (void)rightBarClick:(UIBarButtonItem *)sender {
 3     
 4     // 1.创建视图控制器对象
 5     SecondViewController *secondVC = [[SecondViewController alloc] init];
 6     
 7     
 8     // 第五步:设置代理
 9     secondVC.delegate = self;
10     
11     
12     // 2.push跳转
13     [self.navigationController pushViewController:secondVC animated:YES];
14     
15 }

第六步:实现协议方法

1 // 第六步:实现协议方法
2 - (void)passValueWithString:(NSString *)textString {
3     
4     // 使用代理传过来的值设置要显示的内容
5     self.myLabel.text = textString;
6     
7 }

block传值(从后往前传)

第一步:声明一个block

1 @interface SecondViewController : UIViewController
2 //声明一个block属性
3 @property(nonatomic,strong) void(^block)(NSString *);
4 
5 @end

第二步:调用block

1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
2     [self.navigationController popViewControllerAnimated:YES];
3     //第二步:调用block
4     self.block(self.BlockTextField.text);
5 }

第三步:实现block

1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
2     SecondViewController *secondVC = [[SecondViewController alloc] init];
3     //第三步;实现block
4     secondVC.block = ^void(NSString *textString) {
5         self.userLabel.text = textString;
6     };
7     
8     [self.navigationController pushViewController:secondVC animated:YES];
9 }
原文地址:https://www.cnblogs.com/zhanglida/p/5572362.html