代理

在Swift中,定义协议,要继承自NSObjectProtocol

定义协议示例代码:

 1 import UIKit
 2 
 3 // 定理代理协议,要继承NSObjectProtocol,否则无法使用弱引用
 4 protocol CustomViewDelegate:NSObjectProtocol {
 5     
 6     // 声明代理方法
 7     func delegateMethod()
 8 }
 9 
10 class CustomView: UIView {
11     
12     // 声明代理对象,用weak修饰(前提:协议必须要继承NSObjectProtocol)
13     weak var delegate:CustomViewDelegate?
14     
15     private lazy var button:UIButton = {
16         
17         let button = UIButton()
18         
19         button.addTarget(self, action: #selector(buttonClickAction(btn:)), for: .touchUpInside)
20         
21         return button
22     }()
23     
24     // 执行代理方法
25     @objc private func buttonClickAction(btn:UIButton){
26         
27         // 使用代理对象调用代理方法
28         // ?表示判断前面的对象是否为nil,如果为nil那么后面的代码就不执行了
29         delegate?.delegateMethod()
30     }
31     
32 }

遵守协议并实现代理方法示例代码:

 1 import UIKit
 2 
 3 class ViewController: UIViewController,CustomViewDelegate {
 4     
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         
 8         let customV = CustomView()
 9         
10         // 设置代理对象
11         customV.delegate = self
12     }
13     
14     // 实现代理方法,代理方法也可以在extension中实现
15     // 注:swift中,如果遵守了协议而没有实现非必选代理方法,会报错
16     func delegateMethod() {
17         print("这里实现了代理方法")
18     }
19 }
原文地址:https://www.cnblogs.com/panda1024/p/6216923.html