swift 闭包传值

闭包也能像OC中的Block一样进行反向传值下面直接上例子进行讲解
第一个界面

import UIKit

class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.brownColor()
    }
    
    override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
        let vc2 = ViewController2.init()
        
        vc2.myBlock={color in
            self.view.backgroundColor = color
        }
        
        self.presentViewController(vc2, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

第二个界面

import UIKit
typealias callBlockFunc = (color:UIColor)->()
class ViewController2: UIViewController {
    var myBlock = callBlockFunc?()
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        myBlock!(color: UIColor.redColor())
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

你可能感兴趣的:(swift 闭包传值)