swift3使用协议和泛型简化UITableView的使用(续)多种类型的cell注册

本文介绍了如何在Swift3中使用协议和泛型来简化UITableView中多种类型Cell的注册过程。通过定义协议和泛型方法,实现了在注册和创建Cell时的动态类型识别,使得代码更加简洁高效。
摘要由CSDN通过智能技术生成

1、协议

//
//  ReusableCell.swift
//  reusecell
//
//  Created by targetcloud on 2017/3/26.
//  Copyright © 2017年 targetcloud. All rights reserved.
//

import UIKit

protocol ReusableCell : class{
    static var reuseableIdentifier :String {get}
    static var nib : UINib? {get}
}

extension ReusableCell where Self : UITableViewCell{
    static var reuseableIdentifier :String{
        //return "\(self)"
        //两种实现方式都可以
        print(" --- \(self)  \(String(describing: self)) --- ")
        return String(describing: self)
    }
    
    static var nib : UINib? {
        return nil
    }
}

extension UITableView{
    func registerCell<T : UITableViewCell >(_ cell : T.Type) where T : ReusableCell{
        if let nib  = T.nib{
            register(nib, forCellReuseIdentifier: T.reuseableIdentifier)
        }else{
            register(cell, forCellReuseIdentifier: T.reuseableIdentifier)
        }
    }
    
    func dequeReusableCell<T : UITableViewCell>(indexPath : IndexPath) -> T where T : ReusableCell{
        return dequeueReusableCell(withIdentifier: T.reuseableIdentifier, for: indexPath) as! T
    }
}


2、自定义cell

//
//  TGNib2Cell.swift
//  reusecell
//
//  Created by targetcloud on 2017/3/26.
//  Copyright © 2017年 targetcloud. All rights reserved.
//

import UIKit

class TGNib2Cell: UITableViewCe
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值