我正在制作一个带有 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/