扬庆の博客

Swift 优雅使用 ReuseableIdentifier

字数统计: 439阅读时长: 1 min
2021/03/18 Share

Swift 怎么优雅使用 Reuseable Identifier

使用协议

使用结构体

由于苹果保准UITableView视图的性能,使用了cell重用机制,cell可以通过重用标识符(reusableIdentifier)进行复用,默认的注册cell和获取cell的方法中,需要传入一个字符串作重用标识符. 但这种方式很容易出错,而且使用起来也相当别扭 , 一种普遍的解决方式, 就是直接只用类名作为重用标识符

引出问题

每次都要传入一个类,并且把它转成字符串.所幸,借助Swift泛型特性,我们可以有更加优雅的实现方式 .


使用协议

协议+泛型 优化tableView cells的使用体验.

具体做法很简单:

  1. 声明一个协议,提供并默认实现一个 reuserIdentifier 静态属性
  2. 然后 : 提供一个注册和获取重用cell的方法 (方法放在UITableView的扩展里)
  3. 最后 : 自定义cell 只要遵守了Reusable 协议,就可以通过上面两个方法注册和复用cell了

第一步

1
2
3
4
5
6
7
8
protocol Reusable: class {
static var reuseIdentifier: String {get}
}
extension Reusable {
static var reuseIdentifier: String {
return String(Self)
}
}

第二步

1
2
3
4
5
6
7
8
9

func registerReusableCell<T: UITableViewCell where T: Reusable>(_: T.Type) {
self.registerClass(T.self, forCellReuseIdentifier: T.reuseIdentifier)
}

func dequeueReusableCell<T: UITableViewCell where T: Reusable>(indexPath indexPath: NSIndexPath) -> T{
return self.DequeueReusableCellWithIdentifier(T.reusableIdentifier, forIndexPath: indexPath) as! T
}

将该方法写入 UITableView 扩展里面, 在 UITableView 的代理里面就可以调用该方法达到优雅的重用 cell

使用

1
2
3
4
5
6
7
8
9
# 自定义 cell 里
class AnyCell:UITableViewCell,Reusable { # 自定义 cell 的时候遵守该协议Reusable }

# TableView 代理方法里
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(XSingleBottomAlertCell.self, for: indexPath)
return cell
}

CATALOG
  1. 1. Swift 怎么优雅使用 Reuseable Identifier
    1. 1.0.1. 使用协议
    2. 1.0.2. 第一步
    3. 1.0.3. 第二步
    4. 1.0.4. 使用