我是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
中从AppStore请求数据分析检索到的数据,创建
name
的实例,每个实例都获取它们的名称集,将这些实例存储在数组中viewDidLoad
触发tableView的重新加载
在
App
中检索对应于单元格索引的var apps = [App]()
cellForRowAtIndexPath
在您的App
中关于ios - 无法将已解析的JSON列表显示到TableView中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34528555/