ios - 用字典数据填充 UITableView (Swift)

标签 ios json swift uitableview nsdictionary

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

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

我需要每一个在 TableViewCell 中填充不同的值/标签

最佳答案

如果您想使用 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
}

关于ios - 用字典数据填充 UITableView (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36064687/

相关文章:

ios - SwiftUI 文本对齐

php - iOS - JSONString 到 PHP

ios - 使用设备旋转调整 tableView 的大小

swift - 在 swift 3 中使用扩展时使用未解析的标识符

ios - 在运行时在 objective-c 中获取类对象的大小

ios - 使用 webview 在 iOS 应用程序中伪造位置?

ios - 如何使用计时器停止长时间运行的功能? swift 4

javascript - 动态创建加载更多按钮

python - 如何执行 nvl() 以避免来自不存在的 json 元素的错误?

ios - 动态添加内容到 UIScrollView