在Swift中,定義協議,要繼承自NSObjectProtocolswift
定義協議示例代碼:ide
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 }
遵照協議並實現代理方法示例代碼:spa
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 }