iOS六种传值方式之代理模式

2016-08-21  本文已影响0人  fuxi
  有A、B两个页面,从A页面跳转到B页面,拿到B页面的之后返回A页面并将值显示出来。

实现方式有六种,分别是:代理传值、观察者模式(KVO)、通知、单例模式、block以及非代理。将思路一一总结如下:

1.代理传值

代理模式实现传值的中心思想是通过设置代理对象将值拿到,再通过实现代理方法将值传出去。

a) 要定义好协议,并且写好传值的方法。

//协议:主要实现的功能:传值
@protocol ModalViewControllerDelegate <NSObject>
//协议方法
- (void) changeTextLabelValue: (NSString *) text;

b) 由A页面弹出B页面(这里用了模态视图)

 //1) 创建一个模态视图
ModalViewController *modalViewController = [[ModalViewController alloc] init];

//2. 设置弹窗模式
modalViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

//3. 模态视图
[self presentViewController:modalViewController animated:YES completion:nil];

c) 在B页面设置代理对象,并拿到值
第一步:设置代理对象

  @property(nonatomic, weak) id <ModalViewControllerDelegate> delegate;

第二步:取值

   //1) 取值
    UITextField *textField = (UITextField *)[self.view viewWithTag:2000];

    //2) 传值
    [self.delegate changeTextLabelValue:textField.text];

    //3) 关闭模态视图,回到A页面
    [self dismissViewControllerAnimated:YES completion:nil];

d) 回到A页面,签订协议,给B页面设置好代理对象,实现协议方法,传值

签订协议

 @interface RootViewController : UIViewController <ModalViewControllerDelegate>

给B页面设置好代理对象:

 modalViewController.delegate = self;

实现协议方法,传值:
#pragma mark - 代理方法:值传递
- (void) changeTextLabelValue: (NSString *) text {

        //1) 获取Label
        UILabel *label = (UILabel *)[self.view viewWithTag:1000];

        //2) 传值
        label.text = text;

        }

源代码地址:
https://github.com/zoushuyue/SYDelegateByValue

上一篇 下一篇

猜你喜欢

热点阅读