如何在加载了JSON API数据的tableview单元格中保存checkmark属性?

时间:2018-03-26 16:46:53

标签: swift xcode alamofire swifty-json

我知道在手动将数据添加到阵列时如何保存复选标记。我只是不知道如何在与API同步数据时保存单元格的checkmark属性。

这是我的代码:

class TableViewController: UITableViewController {

    let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Items.plist")
    var fetchCoinInfo = [[String: AnyObject]]()
    let url = "https://api.coinmarketcap.com/v1/ticker/"

    override func viewDidLoad() {
        super.viewDidLoad()
        getCoinData(url: url)
        self.tableView.reloadData()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return fetchCoinInfo.count
    }


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

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

        cell.textLabel?.text = fetchCoinInfo[indexPath.row]["name"] as? String
        cell.detailTextLabel?.text = fetchCoinInfo[indexPath.row]["symbol"] as? String

        return cell

    }

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

        tableView.deselectRow(at: indexPath, animated: true)
            let cell = tableView.cellForRow(at: indexPath)
        if cell?.accessoryType == .checkmark {
            cell?.accessoryType = .none
        }else {
            cell?.accessoryType = .checkmark
        }

    }

    func getCoinData(url: String) {

        // Alamofire parsing code:
        Alamofire.request(url, method: .get)
            .responseJSON { response in
                if response.result.isSuccess {

                    print("Sucess! Got the data")
                    let coinJSON : JSON = JSON(response.result.value!)
                    print(coinJSON)
                   self.updateCoinData(json: coinJSON)

                } else {
                    print("Error: \(String(describing: response.result.error))")
            }
        }
        self.tableView.reloadData()
    }

    // SwiftyJSON code:

    func updateCoinData(json : JSON) {

        if let coinSymbol = json[].arrayObject {
            print(coinSymbol)

            self.fetchCoinInfo = coinSymbol as! [[String: AnyObject]]
        }
        else {
            print("cannot connect to the server")
        }
        self.tableView.reloadData()
    }
}

1 个答案:

答案 0 :(得分:0)

请将新密钥添加到本地JSON对象,状态为复选标记,并在didSelect上更新。您还需要在cellForRowAtIndexPath

中设置附件视图
class glove(object):
    def __init__(self, size, color, is_right):
        self.size = size
        self.color = color
        self.is_right = is_right

    def __repr__(self):
        if self.is_right:
            hand = "right"
        else:
            hand = "left"
        s = "{} {} {}".format(self.size, self.color, hand)
        return(s)

    def __eq__(self, other):
        return isinstance(other, glove) and \
            other.size == self.size and \
            other.color == self.color \
            and other.is_right == self.is_right

    def __hash__(self):
        return hash((self.size, self.color, self.is_right))


gloves = [glove('med', 'black', False),
          glove('med', 'black', True),
          glove('lg', 'black', False),
          glove('lg', 'black', True),
          glove('med', 'brown', False),
          glove('med', 'brown', True),
          glove('lg', 'blue', False),
          glove('med', 'tan', False)]

gloves_set = set(gloves)
unpaired = [g for g in gloves if glove(g.size, g.color, not g.is_right) not in gloves_set]
print(unpaired)