Vadim Nikolaev
Vadim Nikolaev

Reputation: 2132

"Generate" labels from data swift

I have

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

and I want to show it in tableView as in picture:

enter image description here

every element - it's UILabel, I created class TimeViewCell: UITableViewCell where have property var labels = [UILabel]() but I don't know how to push data from my array in my function:

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTime", for: indexPath) as! TimeViewCell
        let showHour = self.infoWripper.sorted(by: { $0.hour < $1.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
    }

Upvotes: 1

Views: 116

Answers (1)

Yannick
Yannick

Reputation: 3278

I would add a UIStackView to your UITableViewCell. You can add the labels with the text to the UIStackView.

I wrapped your data into an array.

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
}

Then, in for your TimeViewCell, you have to add your UIStackView IBOulet (or add it programmatically) and the configure method.

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)
        }
    }
}

Upvotes: 1

Related Questions