版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Mayxc/article/details/102801354
1.定义代理方法:
代码语言:javascript复制@objc protocol ChangeColorDelegate: class {
/// 必须实现的方法
func changeClolor(_ clolor:UIColor)
/// 非必须实现方法
@objc optional func mayChangeClolor() -> UIColor
}
///也可以这样声明:
protocol ChangeColorDelegateSwift: class {
/// 必须实现的方法
func changeClolor(_ clolor:UIColor)
/// 非必须实现方法
}
2.申明代理属性(weak):
代码语言:javascript复制weak var delegate:ChangeColorDelegate?
3.调用代理方法:
代码语言:javascript复制 if ((self.delegate?.changeClolor) != nil) {
self.delegate?.changeClolor(.red)
}
4.在需要调用的地方遵循代理
代码语言:javascript复制bVC.delegate = self
5.在需要调用的地方写代理方法
代码语言:javascript复制extension ViewController:ChangeColorDelegate{
func changeClolor(_ clolor: UIColor) {
self.view.backgroundColor = clolor
}
}
具体使用方法:
B 界面:
代码语言:javascript复制import UIKit
@objc protocol ChangeColorDelegate: class {
/// 必须实现的方法
func changeClolor(_ clolor:UIColor)
/// 非必须实现方法
@objc optional func mayChangeClolor() -> UIColor
}
class BViewController: UIViewController {
weak var delegate:ChangeColorDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .green
// Do any additional setup after loading the view.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//调用代理方法
if ((self.delegate?.changeClolor) != nil) {
self.delegate?.changeClolor(.red)
}
}
}
A界面:
代码语言:javascript复制import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blue
// Do any additional setup after loading the view.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.backgroundColor = .blue
let bVC = BViewController()
// bVC.modalPresentationStyle = .fullScreen
///遵循代理
bVC.delegate = self
self.present(bVC, animated: true, completion: nil)
}
}
///代理方法
extension ViewController:ChangeColorDelegate{
func changeClolor(_ clolor: UIColor) {
self.view.backgroundColor = clolor
}
}