天天看點

swift 學習筆記3 -- OC的block與swift的閉包

目的:兩VC通過閉包傳值

FirstVC.swift裡:

import UIKit

class FirstVC: UIViewController {

    @IBOutlet weak var output: UILabel!

    @IBOutlet weak var ig: UIImageView!

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }

    @IBAction func show(sender: AnyObject) {

        self.ig.image = UIImage(named: "homePY.png");

        let vc = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateViewControllerWithIdentifier("Second") as! Second

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

        let weakSelf = self;

        vc.setClosurePass { (input:String) -> Void in

            weakSelf.output.text = input;

        }

    }

}

SecondVC.swift裡:

import UIKit

typealias PassClosureType = (String) -> Void

class Second: UIViewController {

    @IBOutlet weak var input: UITextField!

    var closurePassValue:PassClosureType?

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }

    func setClosurePass(temClosure:PassClosureType){

        self.closurePassValue = temClosure

    }

    @IBAction func passValue(sender: AnyObject) {

        if let cp = self.closurePassValue {

            if let tex = self.input.text{

                cp(tex)

            }

        }

    }

}