直接上代码吧 - -
Demo地址
https://github.com/Zhangjingwang1993/closureDemo.git
// MainVc
let button = UIButton.init(type: UIButtonType.Custom)
button.frame = CGRectMake(20,100,50,50);
button.backgroundColor = UIColor.cyanColor()
self.view.addSubview(button)
button.addTarget(self,action: Selector("click:"),forControlEvents: UIControlEvents.TouchUpInside)
textField = UITextField.init(frame: CGRectMake(20,160,50));
self.view.addSubview(textField)
textField.placeholder = "I am Placehoder"
func addressThatTakesAClosure(string:String) ->Void{
textField.text = string
}
func click(sender: UIButton)
{
// 初始化
let sec = MainViewController()
// 类似于属性传值
sec.string = "Success"
/***********************************************/
// ---------------华丽的分割线---------------- //
// 用函数把地址传过去,用于回调
// sec.initWithClosure(addressThatTakesAClosure)
// 或者直接这样
sec.myClosure = addressThatTakesAClosure
self.navigationController?.pushViewController(sec,animated: true)
}
// SecVc
// 类似于OC中的typedef
typealias sendValueClosure = (string:String)->Void
var string = ""
// 声明一个Closure(闭包)
var myClosure:sendValueClosure?
// 下面这个方法需要传入上个界面的addressThatTakesAClosure函数指针
func initWithClosure(closure:sendValueClosure?){
myClosure = closure
}
// 类似于OC中的属性传值
print("Success: \(string)")
let label = UILabel.init(frame: CGRectMake(10,150,30))
label.text = string
self.view.addSubview(label)
func backButtonCreate()
{
// 返回按钮
var buttonRight = UIButton()
buttonRight = UIButton.init(type: UIButtonType.Custom)
buttonRight.backgroundColor = UIColor.redColor()
buttonRight.frame = CGRectMake(280,50)
self.view.addSubview(buttonRight)
buttonRight.setTitle("返回",forState: UIControlState.Normal)
buttonRight.addTarget(self,action: Selector("click"),forControlEvents: UIControlEvents.TouchUpInside)
}
// 返回点击方法
func click()
{
if myClosure != nil{
myClosure!(string: string);
} self.navigationController?.popToRootViewControllerAnimated(true)
}