ios - 如何在同一TableView上显示来自JSON的两个不同数据

标签 ios swift

我正在尝试将来自相同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()
    }
}

最佳答案

这是您可以同时显示.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()
        }

关于ios - 如何在同一TableView上显示来自JSON的两个不同数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61827520/

相关文章:

iOS:用多种字体和文本样式显示长页面内容

ios - CGAffineTransformRotate 在执行旋转之前移动对象

ios - 用于创建 iOS 应用程序时导出静态库的符号

ios - 无法使用tvos中的文本字段导出集合将文本字段设置为becomeFirstResponder()

swift - 快速检查 NSError 代码

ios - 如何从链接下载音频文件并将其保存到我的音乐库?

ios - 如何使用 RestKit for iOS 删除服务器上不可用的本地数据库对象

ios - ScrollView 不会快速滚动

swift - 如何将单个字符串发送到 Apple Watch

更改 google、gmail 密码时 iOS Google SDK 失败