TableViewReuse,一句话搞定TableViewCel
2021-06-07 本文已影响0人
编程文学家
TableViewReuse
优点
- TableViewCell、TableViewHeader和TableViewFooter的复用比传统的方式更简单
- 免去了TableViewCell的注册
- 同时支持Objective-C和Swift语言
示例
要运行示例项目,在工程的Podfile中引入TableViewReuse
,运行' pod install '。
安装
TableViewReuse可以通过CocoaPods获得。安装
在你的Podfile中添加以下代码:
pod 'TableViewReuse'
使用
我们可以直接在Swift中使用它,我在Objective-C中 import <TableViewReuse-umbrella.h>
来使用它
Swift场景
复用 Nib 类型 TableViewCell
传统风格:
// Register cell
tableView.register(UINib(nibName: "NibListTableViewCell", bundle: nil), forCellReuseIdentifier: "NibListTableViewCell")
// Dequeue reusable cells
tableView.dequeueReusableCell(withIdentifier: "NibListTableViewCell", for: indexPath)
可以看到,传统的重用tableViewCell方法很麻烦。
现在:
我们有更简便的方式来实现它。
// 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
传统风格:
// Register cell
tableView.register(AnyClassTableViewCell.self, forCellReuseIdentifier: "AnyClassTableViewCell")
// Dequeue reusable cells
tableView.dequeueReusableCell(withIdentifier: "AnyClassTableViewCell", for: indexPath)
现在:
// 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
传统风格:
// Register cell
[tableView registerNib:[UINib nibWithNibName:@"NibListTableViewCell" bundle:nil] forCellReuseIdentifier:@"NibListTableViewCell"];
// Dequeue reusable cells
NibListTableViewCell *cell = tableView.dequeueReusableCell(withIdentifier: "NibListTableViewCell", for: indexPath)
现在:
NibListTableViewCell *cell = [tableView dequeueReusableCellWithNibClass:NibListTableViewCell.class];
重用手写代码类型的TableViewCell
传统风格:
// Register cell
[tableView registerClass:AnyClassTableViewCell.class forCellReuseIdentifier:@"AnyClassTableViewCell"];
// Dequeue reusable cells
AnyClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AnyClassTableViewCell" forIndexPath:indexPath];
现在:
AnyClassTableViewCell *cell = [tableView dequeueReusableCellWithAnyClass:AnyClassTableViewCell.class];