ios - 在按钮单击 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 行
解决方案
我已经看到您的项目,需要进行一些更改,以便从底部添加选定的项目以添加到顶部。
首先更新您的DictionaryTableDelegate
方法如下:
protocol DictionaryTableDelegate {
func didAddnewRow(_ sender: UIButton)
}
然后如下更改委托调用。
@IBAction func addClicked(_ sender: UIButton) {
delegate?.didAddnewRow(sender)
}
items
从更改let
为var
struct SectionList : Codable {
let title : String?
var items : [Item]?
}
同样在这里,sectionList
从更改let
为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()
}
}
}
推荐阅读
- python - 从 zsh 执行时,Automator 在 python 脚本中找不到包导入
- javascript - 如何使用 REST API 数据与 moment isBetween 更新打开/关闭时间
- django - 如何从 django 中的用户配置文件中删除数据
- pygame - pygame中的collidepoint函数是如何工作的?
- javascript - dom加载前的浏览器检查页面
- angular - Angular 上使用 rxjs 的嵌套 API 请求
- flutter - Flutter 崩溃并给出奇怪的信息
- python - 我究竟做错了什么?我的代码告诉我猜测不正确,当它正确时
- java - 相同的查询方法不同的结果;如果对象(不完全)加载到内存中,springboot或hibernate可以阻止查询吗?
- python - 如何在 selenium 中使用 click() 进行循环?