美文网首页
Swift 中代理的详细讲解和使用

Swift 中代理的详细讲解和使用

作者: Flame_Dream | 来源:发表于2019-02-15 10:56 被阅读0次

    前言

        代理是一种设计模式。它允许类(或者Swift中结构体)将自身负责的功能委托给其他的类型的实例示例。

    应用

    接下来举一个列子

    1. 代理实现的VC
    import UIKit
    
    class ViewController: UIViewController,SecondVCDelegate{
       
        @IBOutlet weak var showNameL: UILabel!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        @IBAction func nextBtnAction(_ sender: Any) {
            let nextVC : SecondVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "nextVC") as! SecondVC
            nextVC.delegate = self
            self.present(nextVC, animated: true, completion: nil)
            
        }
        
        @objc func saveName(_ nameStr: String) {
            self.showNameL.text = "请输入姓名:\(nameStr)"
            print("---------------------\(nameStr)")
        }
        
        
    }
    
    
    在这里插入图片描述
    1. SecondVC
    import UIKit
    
    class SecondVC: UIViewController {
        weak var delegate : SecondVCDelegate?
        @IBOutlet weak var inputName: UITextField!
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        
        @IBAction func btnSureAction(_ sender: Any) {
            if self.delegate != nil && (self.delegate?.responds(to: Selector.init(("saveName:"))))!{
                self.delegate?.saveName(inputName.text!)
            }
            
            self.dismiss(animated: true, completion: nil)
        }
        
    }
    
    protocol SecondVCDelegate : NSObjectProtocol {
        func saveName(_ nameStr : String)
    }
    
    
    在这里插入图片描述

    Swift中Delegate细节注意

    一、需要用weak修饰代理(weak var SecondVCDelegate?)

    weak修饰声明的属性避免循环引用的问题(类似OC中的weak修饰)

    二、代理方法的判断(respondsToSelector()在Swift中的使用)

    原因是在OC的代码中, 用respondsToSelector()方法来判断是否实现了方法。
    而在Swift中需要使用 (self.delegate?.responds(to: Selector.init(("saveName:"))))! 的方式判断是否实现这个方法。

    在在代理执行的类中需要使用@objc 修饰saveName方法。(@objc 关键字来达到,Objective-C中使用#selector中使用)

    Swift Delegate详解的: Demo地址
    https://github.com/FlameDream/Delegate_Test

    相关文章

      网友评论

          本文标题:Swift 中代理的详细讲解和使用

          本文链接:https://www.haomeiwen.com/subject/tulpeqtx.html