首页 > 解决方案 > 在 UITableView 中更改数据库 JSON 数组数据的问题

问题描述

我有一个从 JSON 数组填充的 TableView 控制器,TableView 控制器也有一个BarButtonItem名为doneButton.

这个想法是在 tableView 控制器中选择几行并按doneButton. 这应该将status所有选定行的 更改为Done

JSON 数组类似于以下示例:

[
    {
        "customer": "John",
        "status": "Working",
    },
    {
        "customer": "James",
        "status": "Working",
    },
    {
        "customer": "Jamie",
        "status": "Working",
    }
]

结构定义为:var structure = [Structure]()

import UIKit

struct Structure: Codable {
    let customer: String
    let status: String
}

到目前为止的 TableView 委托代码:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isFiltering() {
        return pickup.count
    }
    print(structure.count)
    return structure.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCell(withIdentifier: "testingCell", for: indexPath)


    let portfolio: Structure
    portfolio = structure[indexPath.row]
    cell.textLabel?.text = portfolio.customer
    return cell

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryType = .none

}

选择几个客户名称后选择doneButton状态(未显示在 tableView 中)应更改为Done

更改还应该反映JSON从中提取的 mysql 数据库,如何做到这一点。

标签: iosswiftuitableview

解决方案


您应该在结构 (struct) 中添加一个属性,该属性将保存行的选择状态。所以下次如果 tableview 将被重新加载,它将如此选择行的状态。

struct Structure: Codable {
    let customer: String
    let status: String
    var isSelected: Bool
}

在 tableView(_tableView: UITableView, cellForRowAt indexPath: IndexPath) 方法中添加

if portfolio.isSelected == true {
   cell.accessoryType = . checkmark
} else {
   cell.accessoryType = .done
}

另外,在 tabelview didSelectRowAt 和 didDeselectRowAt 中更改 isSelected 的状态值。

如果您想将此选择保存在数据库中,则必须在表中再创建一列并将所选值保存在数据库中。

我希望这能帮到您。


推荐阅读