【发布时间】:2015-11-23 20:04:50
【问题描述】:
我正在从远程服务器接收 JSON 文件,我可以在标签中显示结果。当我调用函数processJSONData() 时,JSON 数据工作正常,并且 tableview 与简单数组一起工作正常。如何合并两者以在 tableview 中显示 JSON 文件的结果?请查看下面的代码并进行编辑。非常感谢:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var countryLabel: UILabel!
@IBOutlet weak var capitalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//processJSONData()
self.myTableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
self.myTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func processJSONData(){
let urlPath = "http://dubaisinan.host22.com/service1.php"
let url : NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url,completionHandler: {(data, respose, error) -> Void in
if error != nil {
println(error)
}
else {
self.abc(data)
}
})
task.resume()
}
func abc(data:NSData)
{
var parseError: NSError?
let result:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError);
if(parseError == nil){
if let dictResult = result as? NSArray{
dispatch_async(dispatch_get_main_queue()) {
self.countryLabel.text = dictResult[2]["Capital"] as? String
}
}
}
}
@IBOutlet weak var myTableView: UITableView!
var items = ["One","Two", "Three","Four"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.myTableView
.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
}
【问题讨论】:
-
这个问题令人困惑。您只是想在表格视图单元格中添加或使用其他字段和数据吗?
-
嗨迈克尔,我只想将远程数据库中的以下 JSON 结果显示到表格视图中:[{"Country":"Canada","Capital":"Otawa"},{"Country ":"法国","首都":"巴黎"},{"国家":"英格兰","首都":"伦敦"}]。就像我提到的,JSON 文件工作正常,其中一项可以显示在标签中。如何在表格视图中显示信息?谢谢。
-
这完全取决于您希望单元格的外观以及您希望它们显示什么信息。在问题中发布您的示例 JSON,并可能显示您希望表格单元格的外观。
标签: ios json swift uitableview