美文网首页
iOS传值-反向传值-代理(delegate)

iOS传值-反向传值-代理(delegate)

作者: 夜羚 | 来源:发表于2017-11-19 19:29 被阅读52次

在iOS中代理模式的主要作用是反向传值。

场景:  FirstViewController 跳转到SecondViewController, 然后又跳转回 FirstViewController,并将在SecondViewController中textField中输入的数据打印在FirstViewController的firstLabel上。    

步骤一.

    在SecondViewController中创建一个协议 TDdelegate

- (void)TrenData:(NSString *)valueString;为协议方法。该协议方法将会以代理的形式在FirstViewController实现。

啰嗦一句,协议方法分两种

@required //必须实现的方法。

在引入该协议时如果不实现@required下的方法,系统会产经警告

@optional // 可选实现的方法

默认情况下,协议内的方法都是requared必须实现的。


步骤二.

在SecondViewController中声明TDDelegate 协议变量


步骤三.FirstViewController也必须遵循该协议,包含TDDelegate协议。(因为该协议写在“SecondViewController.h”中,FirstViewController包含了这个.h)

步骤四.在FirstViewController实现协议中的方法,firstLabel是FirstViewController中的一个UILabel对象;

步骤五.从FirstViewController进入SecondViewController时设置代理;

步骤六.从SecondViewController回到FirstViewController是,将SecondViewController中的secondTextField的输入值通过协议方法,回传给FirstViewController。

效果如下:

相关文章

网友评论

      本文标题:iOS传值-反向传值-代理(delegate)

      本文链接:https://www.haomeiwen.com/subject/puxuvxtx.html