在按钮单击表视图时快速更新 JSON 数据源



在更新数据源本地 JSON 文件时感到困惑。我有列表显示在带有添加按钮的表格视图中。我需要对按钮事件执行操作以在部分顶部添加特定行。我正在使用代表。基于部分的数据列表。

链接: https://drive.google.com/file/d/1cufp7hHNEVe4zZ7TiSCjFvFLm7EAWuXo/view?usp=sharing

extension DelegateViewController: DictionaryTableDelegate{
func didAddnewRow(_ tag: Int) {
print("Add Button with a tag: (tag)")
AppList?.selectedValue?.append("Welcome")

let indexPath = IndexPath(row: AppData?.sectionList?.count ?? 0 - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
tableView.reloadData()
}

错误: 尝试将第 3 行插入第 0 部分,但更新后第 0 部分中只有 0 行

我已经看到了您的项目,需要进行以下一些更改才能从底部添加所选项目以添加到顶部。

首先更新您的DictionaryTableDelegate方法如下:

protocol DictionaryTableDelegate {
func didAddnewRow(_ sender: UIButton)
}

然后按如下方式更改委托呼叫。

@IBAction func addClicked(_ sender: UIButton) {
delegate?.didAddnewRow(sender)
}

itemslet更改为var

struct SectionList : Codable {
let title : String?
var items : [Item]?
}

同样在这里,将sectionListlet更改为var

struct ListData : Codable {
var sectionList : [SectionList]?    
}

按如下方式更新didAddnewRow代码将解决您的问题:

extension DelegateViewController: DictionaryTableDelegate{
func didAddnewRow(_ sender: UIButton) {
if let cell = sender.superview?.superview as? DictionaryTableViewCell,
let indexPath = self.tableView.indexPath(for: cell)
{
if let selectedItem = AppData?.sectionList?[indexPath.section].items?[indexPath.row] {
let insertIndexPath = IndexPath(item: AppData?.sectionList?[0].items?.count ?? 0, section: 0)
AppData?.sectionList?[0].items?.append(selectedItem)
tableView.beginUpdates()
tableView.insertRows(at: [insertIndexPath], with: .automatic)
tableView.endUpdates()
}
}
}
}

如果要从底部删除所选行,请更新以下代码

func didAddnewRow(_ sender: UIButton) {
if let cell = sender.superview?.superview as? DictionaryTableViewCell,
let indexPath = self.tableView.indexPath(for: cell),
indexPath.section != 0
{
if let selectedItem = AppData?.sectionList?[indexPath.section].items?[indexPath.row] {
let insertIndexPath = IndexPath(item: AppData?.sectionList?[0].items?.count ?? 0, section: 0)
AppData?.sectionList?[0].items?.append(selectedItem)
AppData?.sectionList?[indexPath.section].items?.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.insertRows(at: [insertIndexPath], with: .automatic)
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
}
}
}

最新更新