gpt4 book ai didi

ios - 快速在 TableView 中添加单元格

转载 作者:行者123 更新时间:2023-11-29 00:03:25 25 4
gpt4 key购买 nike

我正在处理表格 View 。在我的 TableView 单元格中,我有两个文本字段,用户可以在其中输入任何数据。 TableView 上还有一个按钮,当用户单击该按钮时可以添加新单元格。新单元格看起来应该与之前显示的单元格相同。我尝试了一些代码,但它不起作用。我的代码是这样的,

extension FlashCardViewController: UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = flashCardTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FlashCardTableViewCell

cell.termTxt.delegate = self
cell.definitionTxt.delegate = self
return cell
}


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 115
}

func textFieldDidEndEditing(_ textField: UITextField) {
allCellsText.append(textField.text!)
print(allCellsText)
}

这是添加新单元格的按钮代码,

 @IBAction func addCardBtnTapped(_ sender: Any) {

let indexPath = IndexPath(row: allCellsText.count+1, section: 0)
flashCardTableView.beginUpdates()
flashCardTableView.insertRows(at: [indexPath], with: .automatic)
flashCardTableView.endUpdates()
view.endEditing(true)
}

当我按下按钮时,应用程序因显示此错误而崩溃,

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

我的观点是这样的, enter image description here

最佳答案

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5 // wrong
return allCellsText.count // correct

}

您只是插入新的单元格,但没有向 numberOfRowsInSection 提供足够的信息。

更新 1:

func numberOfSections {
return 2
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 5
} else {
return allCellsText.count
}

}


@IBAction func addCardBtnTapped(_ sender: Any) {
let indexPath = IndexPath(row: allCellsText.count+1, section: 1) // section 1
flashCardTableView.beginUpdates()
flashCardTableView.insertRows(at: [indexPath], with: .automatic)
flashCardTableView.endUpdates()
view.endEditing(true)
}

关于ios - 快速在 TableView 中添加单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760871/

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