swift 閉包傳值

weixin_33895657發表於2017-08-17

閉包也能像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.
    }
}

相關文章