我有json数据,我需要将它们与表格视图中的标签相匹配,如下图所示: table view
我在UITableViewCell
中有这个代码import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var CompanyLabel: UILabel!
@IBOutlet weak var askPriceLabel: UILabel!
@IBOutlet weak var lastPricelabel: UILabel!
@IBOutlet weak var bidPriceLabel: UILabel!
@IBOutlet weak var highPriceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
这是JSON网址http://tickerchart.com/interview/marketwatch.json
我在uitabledelegate中的尝试:
class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {
var cellData = [TableData]()
.
.
func getTableJSON(completed : @escaping() -> ()) {
print("getJSON here")
let url1 = URL(string:"http://tickerchart.com/interview/marketwatch.json")
let task = URLSession.shared.dataTask(with: url1!) { (data, respond , error) in
if error == nil {
do{
self.cellData = try JSONDecoder().decode([TableData].self, from: data!)
DispatchQueue.main.async{
completed()
}
}catch{
}
}
}
task.resume()
}
.
.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRows = cellData.count
return numberOfRows
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.setupCell(adv: self.cellData[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 230
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
我创建了一个名为tabelData的类,其中包含
import Foundation
struct TableData : Decodable {
let name: String
let askPrice: Int
let lastPrice: Int
let bidPrice: Int
let highPrice: Int
}
答案 0 :(得分:0)
要在tableview中显示数据,首先需要从URL进行json解析。您可以使用以下代码执行此操作。
override func viewDidLoad() {
super.viewDidLoad()
self.getJsonData()
// Do any additional setup after loading the view.
}
func getJsonData()
{
let url = "http://tickerchart.com/interview/marketwatch.json"
let task = URLSession.shared.dataTask(with: URL(string:url)!) { (data, response, error) in
if((error) != nil)
{
}
guard let data = data else
{
print("no data found")
return;
}
do
{
let jsonresponse = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
//print("json resonse is",jsonresponse as! NSDictionary)
print("json resonse is",jsonresponse as! NSMutableArray)
}
catch let jsonerror
{
print("json error");
}
}
task.resume()
}
使用此代码,您将在jsonresponse变量中获取json数组,取一个数组,将该响应存储在该数组中。在tableview的numberofrowsinsection方法中给出该数组计数,并在uitableview的cellforrowatindexpath方法中,从该数组中获取对象并显示在您根据自己的要求拍摄的标签中。