视图ViewController
class ViewController: UIViewController{
@IBOutlet weak var valueLabel: UILabel!
var secVC:SecondController = SecondController()
override func viewDidLoad() {
super.viewDidLoad()
secVC.myClosure = {(text:String) -> Void in
print("\(text)")
self.valueLabel.text = text
}
}
@IBAction func push() {
self.navigationController?.pushViewController(secVC, animated: true)
}
}
视图二
import UIKit
// 闭包
typealias sendValueClosure = (text:String)->Void
class SecondController: UIViewController {
var myClosure:sendValueClosure?
var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.redColor()
textField = UITextField(frame: CGRectMake(30, 100, 260, 30))
textField.borderStyle = UITextBorderStyle.RoundedRect
self.view.addSubview(textField)
let btn = UIButton(frame: CGRectMake(30, 150, 260, 30))
btn.setTitle("click", forState: UIControlState.Normal)
btn.addTarget(self, action: #selector(SecondController.click), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
// 点击这里传值过去
func click() {
let str:String = textField.text!
if (myClosure != nil){
myClosure!(text:str)
}
self.navigationController?.popViewControllerAnimated(true)
}
}
当点击click
运行结果为