Swift 闭包的使用

来源:互联网 发布:跆拳道道服多少钱淘宝 编辑:程序博客网 时间:2024/05/04 11:14
  1. 在二级页面创建闭包

    class DetailViewController: UIViewController {

    // 定义闭包
    typealias callBlock = (_ index:Int)->()
    // 无参数闭包的定义
    typealias otherBlock = ()->()
    // 设置闭包属性
    var sendValueBlock:callBlock!
    var noneParmBlock:otherBlock!
    }

2.二级页面调用闭包

 func dismissBtnClick()  {    if (self.sendValueBlock != nil) {        self.sendValueBlock(1)    }if (self.noneParmBlock != nil ){        //无参闭包        self.noneParmBlock()    }    self.dismiss(animated: true) {     }}

3.. 在一级页面回调

       func tableView(_ tableView: UITableView, didSelectRowAt   indexPath: IndexPath) {    let detailVc = DetailViewController()    detailVc.sendValueBlock = {(index:Int)in        print(index)    }  detailVc.noneParmBlock = {//无参数的闭包回调不需要 in       print("无参闭包调用")    }    self.present(detailVc, animated: true) {    }}
原创粉丝点击