Swift:delegate

2019-11-03 12:44:19 浏览数 (1)

版权声明:本文为博主原创文章,遵循 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
    }
    
   
    
    
}

0 人点赞