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

标签 swift uitableview dictionary

我有一个结构,它保存我从 url 接收到的数据。这段代码在将数据放入名为 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
}
}

最佳答案

tableView 按顺序显示内容。没有订购字典。通过使用“for (key, value) in clubDict”遍历您的字典,您将只会显示字典中的最后一个条目。

你要做的就是把无序的字典变成像数组这样的有序形式。例如像这样:

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

然后您必须调整“numberOfRowsInSection”方法以现在使用 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的字典

关于swift - 如何使用字典中的所有数据填充 tableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47097967/

相关文章:

ios - 将 textField 更改为 textView 时出现问题?

ios - 带有 UIPanGestureRecognizer 的 UITableView 导致 "jumping"触摸

python - 对嵌套字典条目求和

ios - 检测文本字段应该从TableViewController中的Custom UITableViewCell返回以添加新行

python - 如何按定义的顺序遍历 Python 字典?

c# - 在抽象字典中使用枚举 Bastetype 作为键

swift - NSTimer 选择器中的多个参数

ios - 获取错误 [UIImage 范围] : unrecognized selector sent to instance

ios - 如何使用分段控件在一个 TableView 中维护两个自定义单元格?