swift - 如何用 2 个部分填充 UITableView
问题描述
我的问题是 NumberOfRowsInSection 应该读取两个值。
let sections = ["Apples", "Oranges"]
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//Option A)
if apples.count & oranges.count != 0 {
return apples.count & oranges.count
} else {
return 0
}
//Option B)
if sections[0] == "Apples" {
return apples.count
}
if sections[1] == "Oranges"{
return oranges.count
}
return 0
}
所有选项都不起作用,崩溃是因为它没有得到彼此的数量……在 CellForRowAt 上。
另外有人知道如何获得这些部分的标题吗?
解决方案
numberOfRows
将为每个部分调用,因此您需要根据正在查询的当前部分返回正确的值:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? apples.count : oranges.count
}
cellForRowAt
您需要在所有其他数据源/委托方法中使用类似的模式:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", indexPath: indexPath
if indexPath.section == 0 {
cell.titleLabel.text = apples[indexPath.row]
} else {
cell.titleLabel.text = oranges[indexPath.row]
}
return cell
}
这被简化并做了很多假设,但它给了你正确的想法。
对于标题,您需要:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
这个答案还假设您只有基于两个数组变量的两个部分。这远非理想。你真的应该有一个具有所有正确结构的单一数据结构。那么不需要做任何假设。您可以添加更多部分和行,而不必更改任何表格视图代码。
推荐阅读
- azure-devops - Azure 代理配置设置错误 WinHttp 错误:ERROR_WINHTTP_TIMEOUT
- shell - 如何从管道访问环境变量并将其传递给发布管道
- python - 未找到 Pyscopg2 模块
- java - 无法使用具有不同 Spring Boot 版本的库
- python - 做一个 except 继续迭代
- maven - JMeter 与 Jenkins。Maven vs 命令行执行
- javascript - 在 Html.BeginForm 的 onsubmit 参数中使用 return 的目的是什么?
- c# - Windows 无线网络报告是否有编程接口?
- javascript - 为什么我的 create-react-app 命令会产生 web pack 错误?
- gradle - Intellij IDEA 停止提示我导入更改