返回
抛弃UITableView,让列表页开发不再难构建
IOS
2023-12-01 09:30:59
引言
虽然抛弃UITableView只是个标题党,但本文旨在通过一个示例,比较传统实现和最新实现方法,帮助开发人员简化列表页开发。
传统实现:UITableView
过去,UITableView一直是iOS列表页开发的首选控件。然而,UITableView存在一些固有缺点:
- 难以实现复杂布局: UITableView无法轻松实现复杂的列表布局,例如分组标题、可折叠部分或自定义单元格布局。
- 代码冗余: 需要编写大量样板代码来配置UITableView及其数据源。
- 复用性差: 不同的列表页需要不同的代码,导致复用性差。
最新实现:CompositionalLayout
随着iOS 13的发布,CompositionalLayout被引入,作为UITableView的替代方案。CompositionalLayout提供了更高的灵活性,可以轻松创建复杂布局:
- 灵活性: CompositionalLayout允许开发人员定义自己的布局,包括分组、网格和自定义单元格大小。
- 简洁性: 使用CompositionalLayout编写代码更简洁,因为它消除了样板代码。
- 复用性: CompositionalLayout的模块化设计使不同列表页之间的复用变得容易。
示例:比较两种实现
以下示例展示了如何使用UITableView和CompositionalLayout创建简单的列表页:
UITableView实现
// 创建UITableView并配置其数据源
let tableView = UITableView()
tableView.dataSource = self
// 注册自定义单元格
tableView.register(MyTableViewCell.self, forCellReuseIdentifier: "MyCell")
// 在数据源方法中填充单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")!
cell.textLabel?.text = data[indexPath.row]
return cell
}
CompositionalLayout实现
// 创建UICollectionView并配置其数据源
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: createLayout())
collectionView.dataSource = self
// 注册自定义单元格
collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
// 在数据源方法中填充单元格
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCollectionViewCell
cell.label.text = data[indexPath.item]
return cell
}
// 创建布局
private func createLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout { (sectionIndex, environment) -> NSCollectionLayoutSection? in
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(50))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
return section
}
return layout
}
比较
两种实现方式的比较:
特征 | UITableView | CompositionalLayout |
---|---|---|
复杂布局 | 困难 | 轻松 |
代码简洁性 | 复杂 | 简洁 |
复用性 | 差 | 良好 |
结论
通过采用CompositionalLayout,开发人员可以更轻松地构建灵活、易于复用的列表页。它克服了UITableView的固有缺点,提供了创建复杂布局和简化代码所需的工具。虽然完全抛弃UITableView还不现实,但CompositionalLayout无疑是构建现代列表页的更佳选择。