代码之家  ›  专栏  ›  技术社区  ›  Jake2Finn

从json填充单元格时表为空

  •  0
  • Jake2Finn  · 技术社区  · 6 年前

    我试图用json内容填充一个表。除了表中没有显示任何数据外,一切看起来都很好。实际上,下面的代码应该将每个json数据数组的“title”信息显示在一个单元格中。见线

    cell.textLabel?.text=myNewsItems[索引xpath.row].title

    但是,从控制台输出中可以看到,我可以验证新闻数组的解析是否与预期的一样(请参见检查点: print(myNewsS) ).

    知道我遗漏了什么吗?

    迅捷4

    import UIKit
    
    // structure from json file
    struct News: Codable{
        let type: String
        let timestamp: String
        let title: String
        let message: String
    }
    
    class HomeVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
        var myTableView = UITableView()
        var myNewsItems: [News] = []
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
            let displayWidth: CGFloat = self.view.frame.width
            let displayHeight: CGFloat = self.view.frame.height
    
            myTableView = UITableView(frame: CGRect(x: 0, y: 150, width: displayWidth, height: displayHeight - barHeight))
            myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
            myTableView.dataSource = self
            myTableView.delegate = self
            self.view.addSubview(myTableView)
    
            // JSON
    
            let url=URL(string:"https://api.myjson.com/bins/ywv0k")
            let session = URLSession.shared
            let task = session.dataTask(with: url!) { (data, response, error) in
    
                // check status 200 OK etc.
    
                guard let data = data else { return }
    
                do {
                    let myNewsS = try
                        JSONDecoder().decode([News].self, from: data)
                    print(myNewsS)
    
                    DispatchQueue.main.async {
                        self.myTableView.reloadData()
                    }
    
                } catch let jsonErr {
                    print("Error json:", jsonErr)
                }
    
            }
            task.resume()
        }
    
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return myNewsItems.count
        }
    
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = myNewsItems[indexPath.row].title
            return cell
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Shehata Gamal    6 年前

    分配数组

    myNewsItems = myNewsS 
    DispatchQueue.main.async {
        self.myTableView.reloadData()
    }