【问题标题】:Populate UITableView with Dictionary data (Swift)使用字典数据填充 UITableView (Swift)
【发布时间】:2016-03-17 15:15:43
【问题描述】:

我正在制作一个带有 NodeJS 后端的社交网络应用程序。该应用程序通过 GET 请求从与 Node 应用程序关联的 MongoDB 获取其数据。我已经想出了如何将从GET 请求返回的JSON 解析为本机字典,但是在我的TableView 中找不到将字典中的每个对象转换为TableViewCell 的干净方法。字典基本上是这样的:

["username":"personWhoPosted", "taggedUsername":"personWhoIsTagged", "imageURL":"http://urlofimageposted.com"]

我需要它们中的每一个来填充 TableViewCells 中的不同值/标签

【问题讨论】:

  • 您可以遍历字典并将 (key,value) 对的每个值设置为表格视图单元格中的标签吗?

标签: ios json swift uitableview nsdictionary


【解决方案1】:

如果你想使用indexPath,我会保留一个字典键数组的副本。

func fetchData() {
  // ....
  // Your own method to get the dictionary from json
  let self.userDict = ["username":"personWhoPosted", "taggedUsername":"personWhoIsTagged", "imageURL":"http://urlofimageposted.com"]

  // Keep a copy of dictionary key
  let self.userDictKeyCopy = Array(self.userDict.keys)
  // You may want to sort it
  self.userDictKeyCopy.sort({$0 < $1})
}

// Table view delegates

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return self.userDictKeyCopy.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier(kCustomCell) as! CustomTableCell

  // Assuming one section only
  let title = self.userDictKeyCopy[indexPath.row] // e.g. "taggedUsername"

  cell.titleLabel = title
  cell.contentLabel = self.userDict[title] // e.g. "personWhoIsTagged"

  return cell
}

【讨论】:

  • 如果 JSON 类似于 [{"username":"personWhoPosted", "taggedUsername":"personWhoIsTagged", "imageURL":"urlofimageposted.com"}, {"username":" personWhoPosted", "taggedUsername":"personWhoIsTagged", "imageURL":"urlofimageposted.com"}] 里面有多组对象?内部的包含每个帖子的数据。
  • 你需要决定你想做什么。例如,您可以有多个表格视图部分,其中每个部分对应一个帖子。对于这样的事情,最好将三个字典字段直接映射到索引路径的恒定行。例如。 if indexPath.row == 0 {cell. contentLabel = userDict['username']} else if indexPath.row == 1 {...}。或者您可以有一个自定义单元格,它将显示所有三个字段,因此不涉及多个部分。
【解决方案2】:
let yourDict = ["username":"personWhoPosted", "taggedUsername":"personWhoIsTagged", "imageURL":"http://urlofimageposted.com"]

部分的行数

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

所在行的单元格

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    let key = Array(yourDict)[indexPath.row].key
    let value = yourDict[key]
    return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2015-11-09
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    相关资源
    最近更新 更多