[英]How to Display two different data from json on same tableview
I am trying to put 2 diff data from same json on same tableview but I am not able to do, In every case.我试图将来自同一个 json 的 2 个差异数据放在同一个 tableview 上,但在每种情况下我都做不到。 I can put only one.我只能放一个。 I want to display.name and .email at the same time我想同时显示.name 和.email
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()
}
}
here is how you can display.name and.email at the same time.. but instead of creating new cell each time.. use deque这是您可以同时显示.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()
}
If you want to use the default cell provided by Apple.如果要使用 Apple 提供的默认单元格。 You can you textLabel
and detailTextLabel
.你可以textLabel
和detailTextLabel
。 Another better way is creating your custom tableviewcell.另一种更好的方法是创建自定义 tableviewcell。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.