如何使用字典中的所有数据填充tableView?

时间:2017-11-03 14:19:55

标签: swift uitableview dictionary

我有一个结构,用于保存我从网址收到的数据。这个代码都可以很好地将数据放入一个名为clubDict的字典中,但是当它在tableView中显示数据时,我得到了字典中的数据计数但只显示了一个键及其不同的值属性重复。

struct Swifter: Codable {

let id: String?
let address: String?

}

class TableViewController: UITableViewController {

var clubDict: [String: Swifter] = [:]

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let locationDict: Dictionary<String, Any> = ["latitude" : 53.444101, "longitude" : -2.192934]

    let json = ["location" : locationDict] as [String : Any]
    guard let clubLocatorURL = URL(string: "https://us-central1-geofire-46ce2.cloudfunctions.net/Club-Locator") else { return }

    var request = URLRequest(url: clubLocatorURL)
    request.httpMethod = "POST"
    guard let httpBody = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { return }
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = httpBody

    let session = URLSession.shared

    session.dataTask(with: request) { (data, response, error) in

        if let response = response {
            print("Response: \(response)")
        }
        if let data = data {
            do {
                let decoder = JSONDecoder()
                self.clubDict = try decoder.decode([String: Swifter].self, from: data)

                DispatchQueue.main.async {
                    self.tableView.reloadData()

                }

            } catch {

                print("error: \(error)")
            }
        }
        }.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return clubDict.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

for (key, value) in clubDict {
     cell.textLabel?.text = key
     cell.detailTextLabel?.text = value.address

}

    return cell
}
}

1 个答案:

答案 0 :(得分:2)

tableView按顺序显示内容。字典不是有序的。在clubDict&#34;中使用&#34; for(key,value)循环你的字典。你只会得到要显示的字典中的最后一个条目。

您需要做的是将无序字典变为有序形式,如数组。例如:

let dict = ["key1" : "value1"]; // Your dictionary. Use the one you already have
var arr : [(String, String)] = [];
for (key, value) in dict {
    arr.append((key, value));
}

然后你必须调整&#34; numberOfRowsInSection&#34;方法现在使用arr.count

对于每个单元格,将调用cellForRowAtIndexPath方法。 在那里,您通过索引从数组中提取正确的条目:

let (key, value) = arr[indexPath.row]; //read element for the desired cell
cell.textLabel?.text = key
cell.detailTextLabel?.text = value.address

您必须根据需要调整数据类型。我刚拿了一个字符串String:String