美文网首页ios开发那些事
Swift中几种回调的方法

Swift中几种回调的方法

作者: Lin__Chuan | 来源:发表于2017-10-16 22:28 被阅读769次

    在OC中,最常用的回调方式是代理和Block,Swift中有代理,没有Block,取代的是闭包.

    这是别人总结的闭包原理及处理方式,我就不做赘述
    http://www.cocoachina.com/ios/20161201/18250.html

    接下来直接介绍闭包如何实现回调(推荐)
    我们会经常遇到在cell中有按钮点击事件,我们需要在ViewController中做回调处理.
    在一个Cell中

    // 1.定义一个闭包类型
    typealias swiftBlock = (_ btnTag : Int) -> Void
    
    // 2. 声明一个变量
    var callBack: swiftBlock?
    
    // 3. 定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callBackBlock(block: @escaping swiftBlock) {
           callBack = block
    }
    
    // 按钮点击方法
    @IBAction func btnClick(_ sender: UIButton) {
            //4. 调用闭包,设置你想传递的参数,调用前先判定一下,是否已实现
            if callBack != nil {
                callBack!(sender.tag)
            }
    }
    

    在ViewController

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
           let cell = tableView.dequeueReusableCell(withIdentifier:"cellID")
    
           // 实现闭包,获取参数
            deviceCell.callBackBlock { (tag) in
                    print(tag)
            }
            return cell
    }
    

    也可以使用代理方式来做
    在cell中

    //  1. 定协议
    protocol MyDelegate {
        func delegateNeedDo(strMessage:String) -> ()
    }
    
    //  2. 声明变量
    var delegate:MyDelegate?
    
    // 3.  点击调用
    @IBAction func btnClick(_ sender: UIButton) {
            delegate?.delegateNeedDo(strMessage: "\(sender.tag)")
    }
    

    在ViewController中

    首先声明代理
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
             let cell = tableView.dequeueReusableCell(withIdentifier:"cellID")
             cell.delegate = self
             return cell
    }
    
    // 实现代理方法,按钮点击时调用
    func delegateNeedDo(strMessage:String) {
            print(strMessage)
    }
    

    推荐使用闭包
    还有一种方式实现回调,通过selector
    http://www.jianshu.com/p/49eb4a767541

    相关文章

      网友评论

        本文标题:Swift中几种回调的方法

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