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