gpt4 book ai didi

ios - 我想用按钮在 Tableview 中一一显示单元格

转载 作者:行者123 更新时间:2023-11-29 05:54:11 24 4
gpt4 key购买 nike

我不想在桌面 View 上显示所有项目。我想通过按“开始”按钮来显示单元格。但每当我运行下面的代码时。我收到“ fatal error :索引超出范围”

var count = 1
var rowCount: Int = 1 {
willSet {
if count != baslik.count {
count = newValue
tableView.reloadData()
}
}
}


var baslik = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = baslik[indexPath.row]
return cell
}

@IBAction func go(_ sender: UIButton) {
rowCount += 1
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

}

最佳答案

您的 baslik 数组为空

var baslik = [String]()

单元格数量从1开始:

var count = 1
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count
}

当表尝试获取第一个单元格的项目时,它崩溃了:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.textLabel?.text = baslik[indexPath.row] /// 0 is out of range
...
}

为了防止这种崩溃,从 0 开始,仅当数据到达时才增加到 1:

var rowCount: Int = 0 {
willSet {
rowCount = min(baslik.count, newValue)
}
didSet {
guard oldValue != rowCount else { return }
tableView.reloadData()
}
}

var baslik = [String]() {
didSet {
rowCount = 1
}
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowCount
}
... rest same

关于ios - 我想用按钮在 Tableview 中一一显示单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55328218/

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