繁体   English   中英

快速在表格视图中添加单元格

[英]Adding cell in Table view in swift

我正在使用表格视图。 在表格视图单元格中,我有两个文本字段,用户可在其中输入任何数据。 当用户单击按钮时,表视图上还有一个按钮可添加新单元格。 新单元格应与显示的先前单元格相同。 我尝试了一些代码,但是没有用。 我的代码是这样的

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).'

我的观点是这样的 在此处输入图片说明

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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM