swift 中的闭包回调

来源:互联网 发布:js改变全局变量的值 编辑:程序博客网 时间:2024/06/06 02:12

需要注意的 地方

1.第一个页面要实现 回调中的需要做的事件

2.第二个页面要声明 闭包

3. 第二个页面在合适的时候调用闭包

4. 注意swift的语法

一、第一个界面

import UIKit

class ViewController: UIViewController {

    

    let label = UILabel.init(frame: CGRectMake(100, 200, 100, 50))

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        let button =  UIButton.init(type: .Custom)

        button.frame = CGRectMake(100, 300, 100, 100)

        button.backgroundColor = UIColor.brownColor()

        button.setTitle("点我点我", forState: .Normal)

         button.addTarget(self, action: #selector(ViewController.nextViewController), forControlEvents: .TouchUpInside)

        self.view.addSubview(button)

        label.backgroundColor = UIColor.greenColor()

        self.view.addSubview(label);

        

        

    }

   

    func nextViewController() {

        let next = MyViewController()

        next.block = {

            self.label.text = $0

        }

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

    }

    

}

二、第二个界面

import Foundation

class MyViewController : UIViewController {

    

    var block : ((showString:String) -> Void)?

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()

        

        let button = UIButton.init(type: .Custom)

        button.frame = CGRectMake(100, 100, 100, 100)

        button.setTitle("点我点我", forState: .Normal)

        button.addTarget(self, action: #selector(MyViewController.blockAction), forControlEvents: .TouchUpInside)

        button.backgroundColor = UIColor.cyanColor()

        self.view.addSubview(button)

    }

    

    func blockAction()  {

        self.block?(showString: "hello,world")

        self.navigationController?.popViewControllerAnimated(true)

    }    

}

1 0
原创粉丝点击