How to Display two different data from json on same tableview

Viewed 54

I am trying to put 2 diff data from same json on same tableview but I am not able to do! In every case, I can put only one. I want to display .name and .email at the same time

Thanks

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()
    }
}
2 Answers

here is how you can display .name and .email at the same time.. but instead of creating new cell each time .. use 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()
        }

If you want to use the default cell provided by Apple. You can you textLabel and detailTextLabel. Another better way is creating your custom tableviewcell.

Related