如何用 2 个部分填充 UITableView
How to populate UITableView with 2 sections
我的问题是应该读取两个值的 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
}
None 的选项有效,崩溃是因为它没有获得彼此的事物的数量......在 CellForRowAt 上。
还有人知道如何获取这些部分的标题吗?
numberOfRows
将针对每个部分调用,因此您需要 return 基于当前查询部分的正确值:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? apples.count : oranges.count
}
您需要在 cellForRowAt
和所有其他数据 source/delegate 方法中使用类似的模式:
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
}
这是简化的并且做了很多假设,但它给了你正确的想法。
对于headers,您需要:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
此答案还假定您只有基于两个数组变量的两个部分。这远非理想。您真的应该拥有一个具有所有正确结构的单一数据结构。然后不需要做任何假设。您可以添加更多部分和行,而不必更改任何 table 查看代码。
我的问题是应该读取两个值的 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
}
None 的选项有效,崩溃是因为它没有获得彼此的事物的数量......在 CellForRowAt 上。
还有人知道如何获取这些部分的标题吗?
numberOfRows
将针对每个部分调用,因此您需要 return 基于当前查询部分的正确值:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? apples.count : oranges.count
}
您需要在 cellForRowAt
和所有其他数据 source/delegate 方法中使用类似的模式:
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
}
这是简化的并且做了很多假设,但它给了你正确的想法。
对于headers,您需要:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
此答案还假定您只有基于两个数组变量的两个部分。这远非理想。您真的应该拥有一个具有所有正确结构的单一数据结构。然后不需要做任何假设。您可以添加更多部分和行,而不必更改任何 table 查看代码。