gpt4 book ai didi

ios - Swift Static TableView 添加额外的行

转载 作者:搜寻专家 更新时间:2023-11-01 07:10:20 24 4
gpt4 key购买 nike

我正在尝试构建一个包含两个部分的 TableView。第二部分应填充数组中的数据。Storyboard有一个带有静态单元格的 TableView。有两个部分,每个部分有一个单元格。

如果 textSectionTwo 数组中只有一项,它就可以正常工作,但是当其中有更多项时就会中断

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

代码下方:

enum TableViewSections {
case sectionOne
case sectionTwo
}

class TableViewController: UITableViewController {

struct Identifier {
static let sectionOneCell = "SectionOne"
static let sectionTwoCell = "SectionTwo"
}

let textSectionOne = "Section 1"
let textSectionTwo = ["Section 2 - Row 1", "Section 2 - Row 2"]

override func viewDidLoad() {
super.viewDidLoad()

tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier.sectionOneCell)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier.sectionTwoCell)

tableView.reloadData()
}

// MARK: - Table view data source

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch sectionForIndex(section) {

case .sectionTwo?:
return textSectionTwo.count // <- breaks when return is > 1

case nil:
fatalError("Unexpected value")

default:
return super.tableView(tableView, numberOfRowsInSection: section)
}
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch sectionForIndex(indexPath.section) {
case .sectionOne?:
return self.tableView(tableView, sectionOneCellForRowAt: indexPath)

case .sectionTwo?:
return self.tableView(tableView, sectionTwoCellForRowAt: indexPath)

case nil:
fatalError("Unexpected value")
}
}


private func tableView(_ tableView: UITableView, sectionOneCellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.sectionOneCell, for: indexPath)
cell.textLabel?.text = textSectionOne
return cell
}


private func tableView(_ tableView: UITableView, sectionTwoCellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.sectionTwoCell, for: indexPath)
cell.textLabel?.text = textSectionTwo[indexPath.row]
return cell
}


func sectionForIndex(_ index: Int) -> TableViewSections? {
switch index {
case 0:
return .sectionOne

case 1:
return .sectionTwo

default:
return nil
}
}

}

编辑:
this sample code from Appple是类似于我的问题。他们使用静态单元格并通过代码添加内容。

最佳答案

静态表格 View 用于呈现带有静态单元格 UI 和其中数据的表格 View 。它将仅使用您在 Storyboard 中制作的那些单元格。

解决方案:使用动态 TableView 。它将允许您显示任意多的行。

关于ios - Swift Static TableView 添加额外的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45359700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com