代理: 个人理解, 假如存在 A B两个对象
需求: 当B做出动作的时候, 需要A来响应,并做出动作
实现思路:
- B 中 创建的函数
- 通过在 A中创建了B
- B中调用函数, A接收而改变
代码如下:
下载地址:https://download.csdn.net/download/qq_29305413/12676120
A 对象
import UIKit
class ViewController: UIViewController,TestDelegate {
func returuColore(in color: UIColor) {
// 改变自身
self.view.backgroundColor = color
}
func returuTest(in test: String) {
self.title = test
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "点击改变背景"
}
@IBAction func clickPushTestVC(_ sender: Any) {
let testVc = TestVC.init()
testVc.delete = self
self.navigationController?.pushViewController(testVc, animated: true)
}
}
B 对象
import UIKit
@objc
public protocol TestDelegate {
/// 必须执行
func returuColore(in color:UIColor)
/// 选择执行
@objc optional func returuTest(in test:String)
}
class TestVC: UIViewController {
open weak var delete:TestDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func clickChangeColor(_ sender: Any) {
self.delete?.returuColore(in: .yellow)
self.delete?.returuTest?(in: "背景已经改变")
}
}