ios - 我们可以在 swift 的 UITableView 部分中实现部分吗?
问题描述
假设有 aUITableView
有 2 个部分 A 和 B。现在在两个部分中,要显示多个对象的详细信息,例如,如果对象是汽车,那么有多个汽车,名称、颜色、里程要显示在物体。那么如何以最佳方式解决问题,因为我们必须使用它来实现它UITableView
?
我提供了 2 个部分UITableView
。然后,我将对象显示为部分内的行。然后,如果我只显示一个对象的 3 个详细信息,那么我将提供行数为 3*(对象数)。下面的代码写在UITableViewCell
类内部,并通过UIViewController
持有UITableView
对象的数据源方法 cellForRowAt()调用
func configureSectionACellWith(indexPath: IndexPath, data: [Car]) {
var row = indexPath.row
row = row % 3
switch row {
case 0: carNameLabel.text = data[indexPath.row/3].name
case 1: colorLabel.text = data[indexPath.row/3].color
case 2: mileageLabel.text = data[indexPath.row/3].mileage
default:
break
}
}
同样,为了配置Section B的单元格,重复上面的代码。
但正如您可能看到的,很多东西都是硬编码的,比如 row = row % 3,新开发人员很难理解代码。还有重复的代码(配置部分 A 和 B 的单元格)。有没有其他方法,当然是解决这种情况的最佳方法?
解决方案
If the layout/details are likely to be the same for each Section, you can just create one type of cell and use it in both section:
class DetailCell: UITableViewCell {
static let cellID = "DetailCell"
//set up all the images/labels etc
func configure(with car: Car) {
label1.text = car.name
label2.text = car.color
label3.text = car.mileage
}
func configure(with other: SomeOtherType) {. //whatever Section B displays
label1.text = other.property1
label2.text = other.property2
label3.text = other.property3
}
}
You don't need to worry about indexpaths or rows for the cell definition. That's done in the dataSource & delegate functions.
You'll set the number of rows in each section the UITableViewDataSource
's numberOfRows
method, and create all your cells in the cellForRowAt
method. I'll not repeat all the detail here - there are 100s of tutorials and blogs on tableViews - but will give you summary examples so you know what you're heading towards:
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(DetailCell.self, forCellReuseIdentifier: DetailCell.cellID)
//any other setup
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section :
case 0: return carsArray.count //if you're showing cars in section A
case 1: return someOtherArray.count //whatever you;re showing in section B
default: return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DetailCell.cellID, for: indexPath)
if indexPath.section == 0 {
cell.configure(with: carsArray[indexPath.row])
} else if section == 1 {
cell.configure(with: someOtherArray[indexPath.row])
}
//do any further cell set up
return cell
}
推荐阅读
- scala - Scalatest 提供 NaN 的匹配器吗?
- linux - 查找行并在末尾附加文本不起作用
- dynamics-crm - 出现错误,没有为给定实体定义实体映射
- leaflet - 无法使用 Leaflet 和 Leaflet knn 插件选择标记
- objective-c - 使用 AFNetWorking 上传文件是否有文件大小限制?
- java - 为什么使用 Java 的流 API 收集器进行管道分组需要更多时间?
- mongodb - 如何查询每五个文档的字段平均值?
- php - 我的 GET 请求(使用 Guzzle)在关闭客户端服务器之前不会发送(编辑:可能会被另一个请求阻塞?)
- pytorch - 当示例数量未完全除以批量大小时,Pytorch DataLoader 失败
- linux - 如何在将文本转换为 CSV 时从文件中删除双引号?