首页 > 解决方案 > 在按钮单击 tableview swift 上更新 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 行

标签: iosjsonswiftuitableview

解决方案


我已经看到您的项目,需要进行一些更改,以便从底部添加选定的项目以添加到顶部。

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

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

然后如下更改委托调用。

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

items从更改letvar

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

同样在这里,sectionList从更改letvar

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

推荐阅读