Swift代理和传值

第一个视图控制器:

import UIKit

// 遵循协议

class ViewController: UIViewController,SecondVCDelegate

 {

    override func viewDidLoad() {

        super.viewDidLoad()

        

        // 创建一个button

        let button1 = UIButton(frame: CGRectMake(120, 120, 50, 50))

        

        // 修改背景颜色

        button1.backgroundColor = UIColor.redColor()

        self.view.addSubview(button1)

        

        // 点击方法

        button1.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

        

    }

    

    // button点击方法

    func buttonAction(sender:UIButton){

        // 跳转下一个界面

        let secondVC = SecondViewController()

        

        // 属性传值

        secondVC.passValue = "咻"

        

        // 指定代理

        // secondVC.delegate = self

        

        // 定义block

        secondVC.block = { (tempColor:UIColor)->Void in

           self.view.backgroundColor = tempColor

        }

        

        self.navigationController?.pushViewController(secondVC, animated: true)

    }

    

    // 实现代理方法

    func changeColor(tempColor: UIColor) {

        self.view.backgroundColor = tempColor

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

}

/*************************************************************/

代理的六大步骤

1.后页面制定协议

2.前页面代理遵循协议

3.后页面设置代理属性

4.前页面指定代理self

5.后页面发送代理方法命令

6.前页面代理实现代理方法

第二个视图控制器:

import UIKit

protocol SecondVCDelegate {

    // 协议中的方法

    func changeColor(tempColor:UIColor)

}

class SecondViewController: UIViewController {

    // 属性

    var passValue:String?

    // 代理属性

    var delegate:SecondVCDelegate?

    // block属性

    var block:((UIColor)->Void)?

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.cyanColor()

        

        print(self.passValue!)

        self.title = self.passValue

        

        

        // 返回button

        let button2 = UIButton(frame: CGRectMake(120, 120, 50, 50))

        

        button2.backgroundColor = UIColor.blackColor()

        

        button2.addTarget(self, action: "button2Action:", forControlEvents: UIControlEvents.TouchUpInside)

        

        self.view.addSubview(button2)

             

    }

    // button2点击方法

    func button2Action(sender:UIButton) {

    

        // 发送代理方法命令

        // self.delegate?.changeColor(UIColor.redColor())

        

        // 调用block

        self.block!(UIColor.redColor())

        

        // 返回

        self.navigationController?.popViewControllerAnimated(true)

    }

     

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

}

原文地址:https://www.cnblogs.com/Mr-zyh/p/5491333.html