用泛型来优化 TableView Cells 的使用体验

来源:互联网 发布:人工智能武器 编辑:程序博客网 时间:2024/05/20 16:43

介绍

我不喜欢使用字符串做标识符,我认为使用常量要比字符串好很多。

但是,当涉及到 UITableViewCell 或 UICollectionViewCell 以及他们的重用标识符(reuseIdentifiers)时,我想采用一种更加魔幻的解决方案:『使用 Swift 的泛型 + Mixins 的方式』,下面让我们摒住呼吸,见证奇迹的时刻。

魔法时刻

我的想法是在 UITableViewCell(或 UICollectionViewCell)的子类中将 reuseIdentifier 声明为一个静态常量,然后用它使这个 cell 的实例对外部透明化(即,不用显式地使用 reuseIdentifer 来实例化 cell)。

我们首先声明一个协议,以便于稍后能够将其作为 Mixin 来使用:

protocol Reusable: class {
static var reuseIdentifier: String { get }
}
extension Reusable {
static var reuseIdentifier: String {
// 我喜欢使用类名来作为标识符
// 所以这里可以用类名返回一个默认值
return String(Self)
}
}

当我们使用泛型实现 dequeueReusableCell(…) 方法时,魔法出现了:

func dequeueReusableCell<T: Reusable>(indexPath indexPath: NSIndexPath) -> T {
return self.dequeueReusableCellWithIdentifier(T.reuseIdentifier, forIndexPath: indexPath) as! T
}

得益于 Swift 的类型推断,这个方法将使用调用点的上下文来推断 T 的实际类型,因此这个类型可以被看做方法实现中的『复古注入』(retro-injected)!

let cell = tableView.dequeueReusableCell(indexPath: indexPath) as MyCustomCell

注意观察 reuseIdentifier 在内部的使用方法…完全由编译器看到的返回类型决定!那就是我说的类型“复古注射(retro-injected)”,以及为什么我超

原创粉丝点击