使用Reusable优化 UITableviewCell, UICollectionViewcell 的重用

在通常情况下我们 tableview 的 datasource 的写法是

tableView.dequeueReusableCellWithIdentifier("Iden", forIndexPath: indexPath)

使用这个函数返回的值是一个 UITableView, 当我们使用自定义的 TableViewCell 式要对其进行一次强制类型转换, 如下:

tableView.dequeueReusableCellWithIdentifier("Iden", forIndexPath: indexPath) as! TableViewCell

虽然我不推荐在代码中使用强制类型转换,但是在我们能肯定类型的时候使用强制类型转化可以使得代码更加简洁, 函数的返回值直接是我们想要的 Cell 的类型而不用我们强制类型转换, 然后我们就试一下将泛型作为函数的返回值

func foo<T>() -> T

然后我们就是用类拓展来增加一个重用 TableViewCell 的方法, 如下:

extension UITableView {
    func dequeueCustomCellWithIdentifier<T: UITableViewCell>(identifier: String, forIndexPath indexPath: NSIndexPath) -> T {
        return dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! T
    }
}

然后我们来测试一下这段代码的可行性

let cell = tableView.dequeueCustomCellWithIdentifier<TableViewCell>("Cell", forIndexPath:indexPath)

是不是报错了呢, 其实返回值是泛型的函数真正的调用方法是:

let cell: TableViewCell = tableView.dequeueCustomCellWithIdentifier("Cell", forIndexPath:indexPath)

既然类型转换都省了, 那么 identifier 能不能也省略呢, 通常情况下, 我们的 identifier 只是为了区分不同的 cell, 相同类型的 cell 使用不同的 iden 的使用常见还是比较少见的, 所以我们就极端一点,直接使用 类型作为 Cell 的 identifier, 然后我们就有了下面的代码:

    static var iden: String {
        return NSStringFromClass(self)
    }
}
extension UITableView {
    func registerCustomClass(cellClass: AnyClass?) {
        registerClass(cellClass, forCellReuseIdentifier: cellClass?.iden ?? "")
    }
    func dequeueCustomCellWithIdentifier<T: UITableViewCell>(forIndexPath indexPath: NSIndexPath) -> T {
        return dequeueReusableCellWithIdentifier(T.iden, forIndexPath: indexPath) as! T
    }
}

所以我们在注册/重用 cell 的时候就可以这么写

tableView.registerCustomClass(TableViewCell.self)
let cell: TableViewCell = tableView.dequeueCustomCellWithIdentifier(forIndexPath: indexPath)

以上是我本人的一些思路, 实际上已经有人替我们做好这个工作了, 这就是Reusable

Reusable http://https://github.com/AliSoftware/Reusable

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

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,600评论 8 265
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,141评论 1 32
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,210评论 30 471
  • 刚刚和爸爸视频,本来想抱怨一下自己最近的压力的,结果,被爸爸抢先了。 晚上八点五十分,我刚刚上床,在吃睡中过完了了...
    瑭糖君阅读 384评论 1 10
  • 二0一七年十一月七日 作者 李化清 秋深信步到东皋, 满目凄清百趣寥。 流断江涸泥底裸, 枝疏叶落草枯焦。 人稀...
    无为居士_f521阅读 408评论 3 2