"Generate" 来自数据的标签 swift

"Generate" labels from data swift

我有

["06:58"]
["07:13", "07:38", "07:53"]
["08:13", "08:38", "08:53"]
["09:13", "09:33", "09:53"]

我想在 tableView 中显示它,如图所示:

每个元素 - 它是 UILabel,我创建了 class TimeViewCell: UITableViewCell 其中有 属性 var labels = [UILabel]() 但我不知道如何在我的函数中从我的数组中推送数据:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTime", for: indexPath) as! TimeViewCell
        let showHour = self.infoWripper.sorted(by: { [=13=].hour < .hour })

        cell.labelTime.text = showHour[indexPath.row].showHour()

        for data in showHour {

            print(data.showFullTime()) //here you see my example of data in console
        }

        return cell
    }

我会向您的 UITableViewCell 添加一个 UIStackView。您可以将带有文本的标签添加到 UIStackView。

我把你的数据包装成一个数组。

let tableViewData = [["06:58"],
    ["07:13", "07:38", "07:53"],
    ["08:13", "08:38", "08:53"],
    ["09:13", "09:33", "09:53"]]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellTime", for: indexPath) as! TimeViewCell

    cell.configure(data: tableViewData[indexPath.row])

    return cell
}

然后,在您的 TimeViewCell 中,您必须添加 UIStackView IBOulet(或以编程方式添加)和配置方法。

class TimeViewCell: UITableViewCell {

    @IBOutlet var labelStackView: UIStackView!

    func configure(data: Array<String>) {
        for time in data {
            let timeLabel = UILabel()
            timeLabel.text = time
            labelStackView.addArrangedSubview(label)
        }
    }
}