美文网首页
swift 闭包传值

swift 闭包传值

作者: 宁静1致远 | 来源:发表于2017-08-17 12:57 被阅读0次

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

    相关文章

      网友评论

          本文标题:swift 闭包传值

          本文链接:https://www.haomeiwen.com/subject/afwgrxtx.html