在开发中,经常需要用到协议代理模式。比如,进入编辑页面修改数据后,将新数据回传到主界面。





4,编辑页 EditViewController.swift
5,编辑页代理 EditViewControllerDelegate.swift
下面通过一个样例来说明协议代理模式,功能如下:
1,主页面有一个标签和一个修改按钮,点击修改按钮会跳转到编辑页面
2,编辑页面中修改输入框的文字后,点击“确定”则返回主页面,同时主页面的标签值会替换成新值
3,如果点击编辑页面的“取消”按钮则直接返回主页面
效果图如下:



实现过程:
1,首先在storyboard中绘制如下两个界面,同时将主界面的“修改”按钮与编辑页做present modally关联

2,设置编辑页面的Identity为EditView

3,主界面 ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import UIKit class ViewController : UIViewController , EditViewControllerDelegate { @IBOutlet weak var label: UILabel ! override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //页面跳转时 override func prepareForSegue(segue: UIStoryboardSegue , sender: AnyObject ?) { if segue.identifier == "EditView" { //通过seque的标识获得跳转目标 let controller = segue.destinationViewController as EditViewController //设置代理 controller.delegate = self //将值传递给新页面 controller.oldInfo = label.text } } func editInfo(controller: EditViewController , newInfo: String ){ label.text = newInfo; //关闭编辑页面 controller.presentingViewController!.dismissViewControllerAnimated( true , completion: nil ) } func editInfoDidCancer(controller: EditViewController ){ //关闭编辑页面 controller.presentingViewController!.dismissViewControllerAnimated( true , completion: nil ) } } |
4,编辑页 EditViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import UIKit class EditViewController : UIViewController { @IBOutlet weak var textField: UITextField ! var delegate: EditViewControllerDelegate ? var oldInfo: String ? override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view. if oldInfo != nil { textField.text = oldInfo } } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func done(sender: AnyObject ) { delegate?.editInfo( self , newInfo: textField.text) } @IBAction func cancel(sender: AnyObject ) { delegate?.editInfoDidCancer( self ) } } |
5,编辑页代理 EditViewControllerDelegate.swift
1
2
3
4
|
protocol EditViewControllerDelegate { func editInfo(controller: EditViewController , newInfo: String ) func editInfoDidCancer(controller: EditViewController ) } |