TableViewReuse,一句话搞定TableViewCell、Header或Footer的复用

https://github.com/cba023/TableViewReuse

优点

  • TableViewCell、TableViewHeader和TableViewFooter的复用比传统的方式更简单
  • 免去了TableViewCell的注册
  • 同时支持Objective-C和Swift语言

示例

要运行示例项目,在工程的Podfile中引入TableViewReuse,运行’ pod install ‘。

安装

TableViewReuse可以通过CocoaPods获得。安装
在你的Podfile中添加以下代码:

1
pod 'TableViewReuse'

使用

我们可以直接在Swift中使用它,我在Objective-C中 import <TableViewReuse-umbrella.h>来使用它

Swift场景

复用 Nib 类型 TableViewCell

传统风格:

1
2
3
4
// Register cell
tableView.register(UINib(nibName: "NibListTableViewCell", bundle: nil), forCellReuseIdentifier: "NibListTableViewCell")
// Dequeue reusable cells
tableView.dequeueReusableCell(withIdentifier: "NibListTableViewCell", for: indexPath)

可以看到,传统的重用tableViewCell方法很麻烦。

现在:

我们有更简便的方式来实现它。

1
2
3
4
// Call the Swift API for Nib type TableViewCell
let cell = tableView.dequeueReusableCell(nibClass: NibListTableViewCell.self)
// Call the Objective-C API for Nib type TableViewCell
let cell = tableView.dequeueReusableCell(withNibClass: NibListTableViewCell.self) as! NibListTableViewCell

重用手写代码类型的TableViewCell

传统风格:

1
2
3
4
// Register cell
tableView.register(AnyClassTableViewCell.self, forCellReuseIdentifier: "AnyClassTableViewCell")
// Dequeue reusable cells
tableView.dequeueReusableCell(withIdentifier: "AnyClassTableViewCell", for: indexPath)

现在:

1
2
3
4
// Call the Swift API for Any class TableViewCell
let cell = tableView.dequeueReusableCell(anyClass: AnyClassTableViewCell.self)
// Call the Objective-C API for Any class TableViewCell
let cell = tableView.dequeueReusableCell(withAnyClass: AnyClassTableViewCell.self) as! AnyClassTableViewCell

Objective-场景

复用 Nib 类型 TableViewCell

传统风格:

1
2
3
4
// Register cell
[tableView registerNib:[UINib nibWithNibName:@"NibListTableViewCell" bundle:nil] forCellReuseIdentifier:@"NibListTableViewCell"];
// Dequeue reusable cells
NibListTableViewCell *cell = tableView.dequeueReusableCell(withIdentifier: "NibListTableViewCell", for: indexPath)

现在:

1
NibListTableViewCell *cell = [tableView dequeueReusableCellWithNibClass:NibListTableViewCell.class];

重用手写代码类型的TableViewCell

传统风格:

1
2
3
4
// Register cell
[tableView registerClass:AnyClassTableViewCell.class forCellReuseIdentifier:@"AnyClassTableViewCell"];
// Dequeue reusable cells
AnyClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AnyClassTableViewCell" forIndexPath:indexPath];

现在:

1
AnyClassTableViewCell *cell = [tableView dequeueReusableCellWithAnyClass:AnyClassTableViewCell.class];

“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

TableViewReuse,一句话搞定TableViewCell、Header或Footer的复用
https://cba023.github.io/posts/939d9a6c/
作者
陈波
发布于
2021年6月7日
许可协议