我是 swift 的新手,不知道为什么 UITableView
不显示来自 JSON
数组的动态数据。
我想使用 swiftyJSON
从 iTunes 获取热门应用列表,然后根据解析的数据创建一个动态表。
我的问题是,当我运行这段代码时,我得到的所有代码都是 5 行,其中的值相同,如下图所示
我怎样才能使它动态化以及我在哪里弄错了? 提前致谢。
更新代码:
import UIKit
struct Apps {
var name : String!
}
class createTable: UITableViewController {
var tableData = [Apps]()
//Mark Properties
@IBOutlet var appTableView : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Get the #1 app name from iTunes and SwiftyJSON
DataManager.getTopAppsDataFromItunesWithSuccess { (iTunesData) -> Void in
let json = JSON(data: iTunesData)
if let appArray = json["feed"]["entry"].array {
for appDict in appArray {
let appName : String! = appDict["im:name"]["label"].string
let ap = Apps(name: appName)
self.tableData.append(ap)
}
}
}
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Table view cells are reused and should be dequeued using a cell identifier.
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let rowData = self.tableData[indexPath.row]
cell.textLabel!.text = rowData.name
return cell
}
}
输出:
最佳答案
不要请求 cellForRowAtIndexPath
中的数据。例如在 viewDidLoad
中请求数据并触发 tableview 的reload
。
创建一个包含所需数据的自定义类,创建这些自定义类的数组,为每个单元格使用该自定义类的一个元素。
什么是
var appName : String!
if let appArray = json["feed"]["entry"].array {
for appDict in appArray {
appName = appDict["im:name"]["label"].string
}
}
cell.textLabel!.text = appName
应该怎么做?您为每个 单元格运行该代码。您总是多次分配 appName
。 appName
最终将始终是找到的姓氏。因此,所有标签都将获得相同的文本集。
解决方案总结。
- 创建一个类
App
,其中包含一个属性name
(稍后更多) - 在您的
viewDidLoad
中从 AppStore 请求数据 - 解析检索到的数据,创建
App
的实例,为每个实例设置名称,将这些实例存储在数组中var apps = [App]()
- 触发 tableView 的重新加载
- 在您的
cellForRowAtIndexPath
中检索与单元格索引对应的App
return apps.count
在你的numberOfRowsInSection
关于ios - 无法将已解析的 JSON 列表显示到 TableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34528555/