swift 协议简单使用方法

这里记录一下swift协议的最简单用法,使用方法如下:
一、在子控件里定义协议

//定义协议,协议名称最好是“你的类名”+Delegate
protocol WalletButtonCellDelegate {
    //协议方法,可以带参数
    func topUpClick()
}

二、在子控件里定义一个delegate属性

class WalletButtonCell: UITableViewCell {
    //定义一个delegate属性
    open var delegate: WalletButtonCellDelegate?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //初始化子视图代码
        //.........
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

三、在需要回调的地方实现一下协议方法

//MARK: - Action
extension WalletButtonCell {
    @objc private func topUpButtonClick() {
        //重要!这里要判断一下self.delegate是否为nil,防止外界未设置导致闪退
        if self.delegate != nil {
            self.delegate!.topUpClick()
        }
    }
}

四、在控制器里的cellForRowAt方法里设置cell.delegate = self

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell: WalletButtonCell = tableView.dequeueReusableCell(for: indexPath)
            cell.delegate = self
            return cell
        default:
            let cell: WalletAssetCell = tableView.dequeueReusableCell(for: indexPath)
            return cell
        }
    }

五、在控制器里监听协议WalletButtonCellDelegate的回调方法

//MARK: - Action
extension WalletViewController: WalletButtonCellDelegate {
    func topUpClick() {
        navigationController?.pushViewController(TopUpController(), animated: true)
    } 
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,161评论 1 32
  • 协议与委托代理回调在之前的博客中也是经常提到和用到的在《Objective-C中的委托(代理)模式》和《iOS开发...
    苹果上的小豌豆阅读 1,251评论 0 1
  • 姓名:魏正君《六项精进》第270期感谢2组公司:绵阳大北农农牧科技有限公司【日精进打卡第427天】【知~学习】背诵...
    莫心莫肺阅读 45评论 0 0
  • 喝一壶茶 ,饮一杯酒,从此不忘天涯,不念此生。 扫庭前的落叶,品凛冽的秋风,从此闭上眼眸,勿入红尘。 读一本书,携...
    爱吃猫的鱼二号阅读 214评论 0 1