iOS界面传值的方式(7种)

iOS传值的方式

  1. 属性传值
  2. 方法传值
  3. 代理传值(delegate)
  4. block传值
  5. 单例模式方式
  6. 通知notification方式
  7. UserDefault或者文件方式

1.属性传值 

情况:A页面跳转到B页面

  • 这种方法只适用于从前往后传值(上一个页面推到下一个页面)
  • 属性传值第一步需要用到什么数据类型就定义什么样的属性
  • 在上一个页面到下一个页面的选中方法里面将要传的值赋给属性

2.方法传值

与属性传值 一样,但是要通过使用方法传值,可以直接将方法与初始化方法合并,此时当触发FirstViewControlle视图的按钮点击事件并跳转到SecondViewController视图时,在按钮点击事件中可以直接通过重写的SecondViewController视图的初始化方法

传值用

1 @property(nonatomic,retain) NSString *firstValue ;

重写初始化方法,用于传值

1 - (id)initWithValue:(NSString *)value
2 {
3   if (self = [super initWithNibName:nil bundle:nil]) {
4         self.firstValue = value;
5   }
6   return self;
7 }

方法传值:

1 - (void)buttonAction:(UIButton *)button {
2 //将方法传值与初始化写到一起
3 SecondViewController *second = [[SecondViewController alloc]
4 initWithValue:_txtFiled.text];
5 
6 //此时已经将值存在firstValue中
7 [self.navigationController pushViewController:second animated:YES];
8 }

3.代理传值(delegate)

情况:A页面跳转到B页面,B页面再返回A页面

UI中的协议为当前类名 + Delegate

  1. 声明代理
  2. 代理对象执行协议
  3. 指定第二个界面的代理对象为自己
  4. 接收协议
  5. 实现协议中的方法

4.block传值

  1. 定义bolock
  2. 声明block类型的属性
  3. block的实现
  4. 调用block

5.单例模式方式

单例只会对某个类实例化一次/单例类,对单例这个类实例化一次有且仅有一个对象

6.通知notification方式

7.UserDefault或者文件方式

原文地址:https://www.cnblogs.com/xs514521/p/5201254.html