如何在UITableView中使用多标签?

问题描述 投票:0回答:1

我从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
    }

}
swift uitableview uikit uilabel iboutlet
1个回答
1
投票

您可以使用UITableViewCell.CellStyle.subtitle,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "groupCell")
    if cell == nil {
        cell = UITableViewCell(style: .subtitle, reuseIdentifier: "groupCell")
    }

    let user = self.dataSource[indexPath.row]
    cell.textLabel?.text = user.firstName + " " + user.lastName
    cell.detailTextLabel?.text = user.email
    return cell
}

您不需要注册单元格,因此删除以下行:

tableview.register(UITableViewCell.self, forCellReuseIdentifier: "groupCell")
© www.soinside.com 2019 - 2024. All rights reserved.