在 iOS 的 table 中增加细胞计数而不增加数据
increase cell count without increasing data in table of iOS
我的数据集就像
var data = [["1"],["2","3"],["4"]]
我想在 table 视图中显示它
我可以使用
cell.textlabel?.text = data[indexPath.section][indexPath.row]
我在导航栏中有一个按钮,当我单击该按钮时,所有部分的行都将增加 1,而不会更改数据中的任何内容
所有新创建的单元格文本字段都应该显示 "add here"
我的 rowat 单元格
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textlabel?.text = data[indexPath.section][indexPath.row]
return cell
我应该如何更改行的单元格,这样我就不会得到超出范围的致命错误索引
声明一个名为 extraRows 的变量并将其初始值指定为 0,并向其添加一个 属性 观察器,以便在它发生变化时重新加载 tableView
var extraRow : Int = 0 {
didSet {
self.tableView.reloadData()
}
}
点击添加按钮后,更新extraRow为+1
@IBAction func addBtnClicked(_ sender : Any) {
extraRow = extraRow + 1
}
此外,更新您的行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count + extraRows
}
除此之外,您还需要更新您的 tableview cellForRowAtIndexPath 并检查 if indexPath.row > data.count
,然后显示您的空 celll
添加到@iOSArchitect.com 的回答中,
您应该检查 cellForRowAt 中的索引。
您获得索引超出范围异常的原因是因为您的 numberOfCell 计数增加但单元格的数据源保持不变。
所以,
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if indexPath.row < data[indexPath.section].count{
cell.textlabel?.text = data[indexPath.section][indexPath.row]
}else{
cell.textlabel?.text = "add here"
}
return cell
这可能不是准确的代码,但我希望您能从中得到合乎逻辑的答案。
我的数据集就像
var data = [["1"],["2","3"],["4"]]
我想在 table 视图中显示它 我可以使用
cell.textlabel?.text = data[indexPath.section][indexPath.row]
我在导航栏中有一个按钮,当我单击该按钮时,所有部分的行都将增加 1,而不会更改数据中的任何内容 所有新创建的单元格文本字段都应该显示 "add here"
我的 rowat 单元格
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textlabel?.text = data[indexPath.section][indexPath.row]
return cell
我应该如何更改行的单元格,这样我就不会得到超出范围的致命错误索引
声明一个名为 extraRows 的变量并将其初始值指定为 0,并向其添加一个 属性 观察器,以便在它发生变化时重新加载 tableView
var extraRow : Int = 0 {
didSet {
self.tableView.reloadData()
}
}
点击添加按钮后,更新extraRow为+1
@IBAction func addBtnClicked(_ sender : Any) {
extraRow = extraRow + 1
}
此外,更新您的行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count + extraRows
}
除此之外,您还需要更新您的 tableview cellForRowAtIndexPath 并检查 if indexPath.row > data.count
,然后显示您的空 celll
添加到@iOSArchitect.com 的回答中, 您应该检查 cellForRowAt 中的索引。 您获得索引超出范围异常的原因是因为您的 numberOfCell 计数增加但单元格的数据源保持不变。
所以,
let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if indexPath.row < data[indexPath.section].count{
cell.textlabel?.text = data[indexPath.section][indexPath.row]
}else{
cell.textlabel?.text = "add here"
}
return cell
这可能不是准确的代码,但我希望您能从中得到合乎逻辑的答案。