swift - 闭包回调

在需要返回数据的页面secondViewController
1.定义一个闭包

typealias KButtonBlock = (_ str :String) ->()

2.声明一个闭包

var noDataBtnBlock: KButtonBlock!

3.返回数据

if noDataBtnBlock != nil {
    noDataBtnBlock(text.text!)
}

完整代码

import UIKit
//另命名一个闭包
typealias KButtonBlock = (_ str :String) ->()

class secondViewController: UIViewController {
    //声明一个闭包
    var noDataBtnBlock: KButtonBlock!
    
    @IBOutlet weak var text: UITextField!
    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.
    }
    
    @IBAction func fanhui(_ sender: Any) {
        if noDataBtnBlock != nil {
            noDataBtnBlock(text.text!)
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

在接收回调数据的页面ViewController
方法一:

let second = segue.destination as! secondViewController
       second.noDataBtnBlock = { (str) -> Void in
       self.text1.text = str
}

方法二:

let third = segue.destination as! ThirdViewController
third.noDataBtnBlock2 = getdata
/*
定义一个带字符串参数的闭包
*/
fileprivate func getdata(str: String)->Void{
   self.text2.text = str
}

完整代码

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var text2: UILabel!
    @IBOutlet weak var text1: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "haha" {
            let second = segue.destination as! secondViewController
            second.noDataBtnBlock = { (str) -> Void in
                self.text1.text = str
            }
        }else{
            let third = segue.destination as! ThirdViewController
            third.noDataBtnBlock2 = getdata
            
        }
        
    }
    /*
     定义一个带字符串参数的闭包
     */
    fileprivate func getdata(str: String)->Void{
        self.text2.text = str
    }
}

你可能感兴趣的:(swift - 闭包回调)