以下示例是关于Swift中包含委托制定协议用法的示例代码,想了解委托制定协议的具体用法?委托制定协议怎么用?委托制定协议使用的例子?那么可以参考以下相关源代码片段来学习它的具体使用方法。
委托是一个对象告诉另一个对象的一种方式 协议 - 在其他编程语言中,称为类接口. 该协议是在课堂之外创建的.协议仅包含函数的标题(和变量 - 但这不太常见).该功能的实现将在课堂上. 委托 - 创建代表类的对象的类. (UiviewController)委派 - 发送事件通知的类. (第二视图controller) 在委派中: 1.创建协议. 2.创建弱委托链接 3.致电代表弹奏 在代表中: 1.订阅委托协议 2.实施委托弹 3.将自我链接到委派对象(controller.delegate = self) !
//1 Creating protocol
protocol SecondViewControllerDelegate: AnyObject {
func vcWasClosed()
}
class SecondViewController: UIViewController {
//2 Creating weak delegate link
weak var delegate: SecondViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func goBackPressed(_ sender: UIButton) {
//3 Call delegate link
delegate?.vcWasClosed()
self.navigationController?.popViewController(animated: true)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func gotoSecondPressed(_ sender: UIButton) {
guard let controller = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else { return }
//3. Link self to delegating object
controller.delegate = self
self.navigationController?.pushViewController(controller, animated: true)
}
}
// 1. Subscribe to delegate protocol
extension UIViewController: SecondViewControllerDelegate {
//2. Implement delegate func
func vcWasClosed() {
print("Hello")
}
}
本文地址:https://www.itbaoku.cn/snippets/785416.html