ios - 如何在同一个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()
}
}
解决方案
这是您如何同时显示 .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()
}
推荐阅读
- arm - ARM cortex M系列中的HPROT[3:0]是如何确定的?
- django - Django:更改项目文件夹/设置结构
- php - 访客计数器,仅统计 24 小时内的唯一访客并结束会话
- android - 导航组件popUpTo bug
- javascript - 为什么我的ajax数据是空的,即使ajax之前的变量输出是对的?
- html - 将一个 link_to 嵌套在另一个 link_to 中
- ruby-on-rails - Rails:在 Docker 中使用 Figaro 定义的环境变量
- python - Django AD 集成获取 AADSTS50011:请求中指定的回复 url 与为应用程序配置的回复 url 不匹配:
- powershell - 如何使用 powershell 设置远程软件安装的安装选项?
- sql - SSRS 表示方差 %