swift 闭包传值

2017-08-17  本文已影响0人  宁静1致远

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

import UIKit

class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.brownColor()
    }
    
    override func touchesBegan(touches: Set<UITouch>, 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<</span>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.
    }
}
上一篇下一篇

猜你喜欢

热点阅读