用字典数据填充UITableView(Swift)

时间:2022-05-14 15:39:54

I'm making an social networking app with a NodeJS backend. The app gets its data from the MongoDB associated with the Node app with a GET request. I have figured out how to parse the JSON returned from the GET request as a native Dictionary, but can not find a clean way of turning each of the objects in the dictionary into a TableViewCell in my TableView. The Dictionary is basically this:

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

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

I need each of those to fill different values/labels inside the TableViewCells

我需要在TableViewCells中填充不同的值/标签

1 个解决方案

#1


2  

If you want to utilize indexPath, I would keep a copy of array of dictionary keys.

如果你想利用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
}

#1


2  

If you want to utilize indexPath, I would keep a copy of array of dictionary keys.

如果你想利用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
}