首页 > 解决方案 > 如何在同一个tableview上显示来自json的两个不同数据

问题描述

我正在尝试将来自同一个 json 的 2 个差异数据放在同一个 tableview 上,但我做不到!在每种情况下,我只能放一个。我想同时显示 .name 和 .email

谢谢

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var userInfo = [UserData]()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        JsonDownload
            {

                self.tableView.reloadData()
           }
        tableView.delegate = self
        tableView.dataSource = self

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userInfo.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = userInfo[indexPath.row].name


        return cell
    }

    func JsonDownload(completed: @escaping () -> ()) {

        let source = URL(string: "https://jsonplaceholder.typicode.com/users")

        URLSession.shared.dataTask(with: source!) { (data, response, error) in

            if let data = data {
                do
                {
                    self.userInfo = try JSONDecoder().decode([UserData].self, from: data)

                    DispatchQueue.main.async
                    {
                        completed()
                    }
                }
                catch
                {
                    print("Json Error")
                }
            }
        }.resume()
    }
}

标签: iosswift

解决方案


这是您如何同时显示 .name 和 .email 的方法.. 但不是每次都创建新单元格.. 使用 deque

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         if  let cell = tableView.dequeueReusableCell(withIdentifier: "Cell"){
            cell.textLabel?.text = userInfo[indexPath.row].name
            cell.detailTextLabel?.text = userInfo[indexPath.row].email

            return cell
          }
            return UITableViewCell()
        }

推荐阅读