Swift 2.2 协议和代理

一:代理 

    两个类之间的传值,类A调用类B的方法,类B在执行过程中遇到问题通知类A,这时候我们需要用到代理(Delegate)。

    比如:控制器(Controller)与控制器(Controller)之间的传值,从C1跳转到C2,再从C2返回到C1时需要通知C1更新UI或者是做其它的事情,这时候我们就用

到了代理(Delegate)传值。

二:协议

    上面说的两个界面,或者类之间的值传递,你就把协议当成他们之间的合同,就理解了。

    下面看看Swift代码怎么写协议,为了方便阅读,我这里把整个Swift文件代码插入了,不是只写了一个方法。这样我自己觉得阅读性更强一点!import UIKit

// 协议的创建
protocol youname{
    
    func younameis(name:NSString) -> Void
}

class ProfileViewController: UIViewController{
    
   // 声明一个协议类型的代理变量
    var delegate:youname!

    // 这个方法写在这里只是为了在后面的界面设置了代理之后,去调用这个方法。
    func delegatetest() -> Void {
        
        self.delegate.younameis("caoxiaocaoxiangni")
    }
   // 这里的思路其实和我们OC写的思路是一样的!
 
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor=UIColor.whiteColor()
    }
  
    override func didReceiveMemoryWarning() {
        
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    /*
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}

     我们来看看第二个界面里面是怎么写的,上面一个是 ProfileViewController 控制器,push 到下一个控制器,MEViewController 中。

import UIKit

class MEViewController: UIViewController,youname {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        // 创建了变量,设置代理,遵守协议,调用方法。
        let you : ProfileViewController = ProfileViewController()
        you.delegate=self
        you.delegatetest()
        
    }
    // 上个控制器里面  delegatetest 这个方法中,我们又设置了让它的代理(其实就是MEViewController)调用 younameis 方法,前面界面的参数 caoxiaocao 也就传了过来!

    func younameis(name: NSString) {
     
           print(name) // caoxiaocao
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    /*
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}

这样子,我也就完整的吧上个界面的值,传到了这个界面中来了。整个思路和OC的差不多。

原文地址:https://www.cnblogs.com/zhangxiaoxu/p/5333681.html