- 1.跳转到需要回调的页面
let test = ViewController() //跳转的页面
test.FuncCallbackValue { (value) -> Void in
print(value)
} //闭包回调函数
self.navigationController?.pushViewController(test, animated: true) //跳转
- 2.跳转的页面
import UIKit
class ViewController: UIViewController {
typealias CallbackValue=(value:String)->Void //类似于OC中的typedef
var myCallbackValue:CallbackValue? //声明一个闭包
func FuncCallbackValue(value:CallbackValue?){
myCallbackValue = value //返回值
}
}override func viewDidLoad() {
super.viewDidLoad()
if (myCallbackValue != nil){
myCallbackValue!(value: "我返回值了")//回调。
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
- 3 嵌套方法
func Gettest (str:String,callback: ((isOK: Bool)->Void)?){
let test=str
callback?(isOK:true)
}
使用
Gettest("test"){ (isOK) in
print(isOK)
}
或者
Gettest("", callback: testcallback)
private func testcallback(isOK: Bool){
if (isOK) {
//do good stuff here
}else{
// do error handling here
}
}