繁体   English   中英

用字典数据填充 UITableView (Swift)

[英]Populate UITableView with Dictionary data (Swift)

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

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

我需要每一个来填充TableViewCell s 内的不同值/标签

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM