[英]Populate UITableView with Dictionary data (Swift)
I'm making an social networking app with a NodeJS backend.我正在制作一个带有 NodeJS 后端的社交网络应用程序。 The app gets its data from the MongoDB associated with the Node app with a
GET
request.该应用程序通过
GET
请求从与 Node 应用程序关联的 MongoDB 获取其数据。 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
.我已经想出了如何将从
GET
请求返回的 JSON 解析为本机字典,但找不到将字典中的每个对象转换为TableViewCell
中的TableView
的干净方法。 The Dictionary is basically this:字典基本上是这样的:
["username":"personWhoPosted", "taggedUsername":"personWhoIsTagged", "imageURL":"http://urlofimageposted.com"]
I need each of those to fill different values/labels inside the TableViewCell
s我需要每一个来填充
TableViewCell
s 内的不同值/标签
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
}
let yourDict = ["username":"personWhoPosted", "taggedUsername":"personWhoIsTagged", "imageURL":"http://urlofimageposted.com"]
Number of rows in section节中的行数
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourDict.count
}
Cell for row at行的单元格在
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.