I have a table view in the cell i'm having two text fields in which user can enter the data. Initially i'm showing 5 cells. There is a button on which when user click it add one more cell in the table view. Now when i hit a button it add a cell when textfields are empty. But when i add data in all 5 cell textfields and than hit add button app crashes by showing this error, Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 10 into section 0, but there are only 6 rows in section 0 after the update'
The code is try for adding and deleting cell is this,
extension FlashCardViewController: UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfCell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = flashCardTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FlashCardTableViewCell
//cell.termTxt.delegate = self
//allCellsText[indexPath.row] = cell.termTxt.text!
// cell.definitionTxt.delegate = self
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 115
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
numberOfCell -= 1
allCellsText.remove(at: indexPath.row)
flashCardTableView.beginUpdates()
flashCardTableView.deleteRows(at: [indexPath], with: .automatic)
flashCardTableView.endUpdates()
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
allCellsText.append(textField.text!)
print(allCellsText)
}
}
The code for add button is this,
@IBAction func addCardBtnTapped(_ sender: Any) {
numberOfCell += 1
let indexPath = IndexPath(row: allCellsText.count+1, section: 0)
flashCardTableView.beginUpdates()
flashCardTableView.insertRows(at: [indexPath], with: .automatic)
flashCardTableView.endUpdates()
view.endEditing(true)
}
When i delete any cell it gives me error of index out of range. How can i achieve this goal? The view controllers looks like this,