美文网首页iOS
swift 闭包回调

swift 闭包回调

作者: _swift_ | 来源:发表于2015-12-07 19:21 被阅读511次
  • 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
    }
}

相关文章

网友评论

    本文标题:swift 闭包回调

    本文链接:https://www.haomeiwen.com/subject/owcehttx.html