【发布时间】:2019-04-01 14:22:23
【问题描述】:
我从 JSON(名字、姓氏和电子邮件)获取数据,但我只能在 UITableView 中显示名字。我尽了最大的努力,但我无法让它发挥作用。以下是我的代码。
import UIKit
struct User: Codable {
let firstName: String
let lastName: String
let email: String
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case email = "email"
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableview: UITableView!
private var dataSource = [User]() {
didSet {
self.tableview.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.register(UITableViewCell.self, forCellReuseIdentifier: "groupCell")
self.tableview.dataSource = self
self.tableview.delegate = self
let url = URL(string: "https://x.com/x.php")
URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "An error occurred")
return
}
DispatchQueue.main.async {
self?.dataSource = try! JSONDecoder().decode([User].self, from: data)
}
}).resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath)
let user = self.dataSource[indexPath.row]
cell.textLabel?.text = user.firstName
// cell.textLabel?.text = user.lastName If I write this line then it only shows last name
return cell
}
}
【问题讨论】:
-
看起来您正在使用默认
UITableViewCell并且还有一个属性detailTextLabel可以与它一起使用。但是如果你想显示更多的数据你需要创建自定义UITableViewCell -
另外,您可以将
JSONDecoder的keyDecodingStrategy设置为convertFromSnakeCase,这样就可以避免声明自己的CodingKeys枚举 -
我更新了代码并创建了自定义标签,但 xcode 找不到我的标签。代码在上面。谢谢你的帮助。 @Dharmesh
-
你需要通过添加
as! tableViewCellLabels来投射你的cell -
我应该在哪里写这个?在最后一个函数而不是 UITableViewCell 之后 -> ? @Dharmesh
标签: swift uitableview uikit uilabel iboutlet