美文网首页
Delegate委托的使用

Delegate委托的使用

作者: 雅风丶 | 来源:发表于2018-07-17 19:18 被阅读0次

    委托的说明

    委托(delegate)是Cocoa的一个术语,表示将一个对象的部分功能转交给另一个对象。

    比如对象A希望对象B知道将要发生或已经发生某件事情,对象A可以把对象B的引用存为一个实例变量。这个对象B称为委托。当事件发生时,它检查委托对象是否实现了与该事件相适应的方法。如果已经实现,则调用该方法。

    由于松耦合的原因,一个对象能成为多个对象的委托。某些情况下,相较于通过继承让子类实现相关的处理方法,可以有效减少代码复杂度。所以iOS中也大量的使用了委托。

    委托的实例

    //定义个协议
    protocol loadingDeleagte {
        func didLoading(text: String)
    }
    class HomeViewController: UIViewController {
    
        @IBOutlet weak var textFlied: UITextField!
        
        //2.声明一个委托代理
        var delegate: loadingDeleagte?
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
        }
        
        @IBAction func backBtnClick(_ sender: AnyObject) {
            
            print("点击了")
            //3实例一个 ViewController类
            let loading = ViewController()
            //指定委托代理是 loading 的实例
            delegate = loading
            //调用委托实现的协议方法
            delegate?.didLoading(text: textFlied.text!)
        }
     
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            
            UIApplication.shared.keyWindow?.endEditing(true)
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        
    
      
    }
    
    import UIKit
    
    class ViewController: UIViewController {
    
        
        @IBOutlet weak var textLable: UILabel!
        @IBOutlet weak var NextBtn: UIButton!
        override func viewDidLoad() {
            super.viewDidLoad()
        
       
            
        }
    
    }
    
    //4实现LoadingDelegate协议
    extension ViewController : loadingDeleagte {
    
        func didLoading(text: String) {
        
            print(text)
            
            //值已经传过来了
            
        }
    }
    

    实际开发中容易遇到的问题

    • 实际开发中容易遇到的问题
      1.新建的另一个页面的的controller对象,不是要跳转的页面的controller。
      2.delegate没有设置好,导致获取不到对应controller的控件
    • 关键解决方法:
    //获取到对应页面的controller
    let secondView = self.storyboard?.instantiateViewController(withIdentifier: "second") as! addTagsViewController
            //设置secondView中的代理为当前ViewController自身
            secondView.delegate=self
            self.navigationController!.pushViewController(secondView,animated:true)
    

    secondView中传值回去

    if((delegate)) != nil{
                delegate?.didLoading(text: "传值回去")
                self.navigationController?.popViewController(animated: true)
    

    参考资料

    http://www.hangge.com/blog/cache/detail_810.html

    https://www.cnblogs.com/ningmengcao-ios/p/5952872.html

    相关文章

      网友评论

          本文标题:Delegate委托的使用

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