hwollersheim
hwollersheim

Reputation: 81

How to create an unknown number of UILabels in a UITableViewCell?

I'm building an iOS app that uses a UITableView to display events scheduled for the next 7 days.

The class ThisWeekViewController fetches events persisted in a database based on a given date and returns an array of strings that contains the names of all events for that date, called `projectNamesForCurrentDay.

Inside my TableView, I'm using a custom UITableViewCell class called ThisWeekTableViewCell that should hold a day number, day name and below that a bullet-style list displaying all projects scheduled for that day:

enter image description here

I've spent the best part of the week trying to figure out the best way to handle the programmatic, conditional creation and placement of the labels inside my Cell, but I'm still not sure how I should solve this problem properly. Obviously, the array holding my event names can be used to determine the number of labels needed and the text property for each one of them. But should the labels be created and configured inside the cell itself or in the ViewController? And if the former is the case, how do I access the array of event names from inside my cell class?

Upvotes: 2

Views: 133

Answers (1)

Amit
Amit

Reputation: 4896

Try this :

I have tried with an example. you can further change it according to your requirement.

View Controller :

class ViewController: UIViewController {

    let dict1: [String:Any] = ["Date": "31", "Name": "Yesterday", "Meetings": ["Abc","Abc","Abc","Abc","Abc","Abc","Abc","Abc"]]
    let dict2: [String:Any] = ["Date": "1", "Name": "Today", "Meetings": ["Abc","Abc","Abc","Abc","Abc"]]
    let dict3: [String:Any] = ["Date": "2", "Name": "Tomorrow", "Meetings": ["Abc","Abc","Abc"]]

    var arrayData:[[String: Any]] = []

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        arrayData = [dict1, dict2,dict3]

        tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "cellReuse")
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuse", for: indexPath) as! CustomTableViewCell

        cell.populate(data: arrayData[indexPath.row])
        return cell
    }
}

Custom Table View Cell:

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var stackView: UIStackView!

    func populate(data: [String: Any]) {
        dateLabel.text = data["Date"] as? String
        nameLabel.text = data["Name"] as? String

        guard let meetingsArray = data["Meetings"] as? [String] else {
            return
        }

        for views in stackView.arrangedSubviews {
            views.removeFromSuperview()
        }
        for meeting in meetingsArray {
            let label = createLabel(meeting: meeting)
            stackView.addArrangedSubview(label)
        }
    }

    func createLabel(meeting: String) -> UILabel {
        let label = UILabel()
        label.textColor = UIColor.black
        label.numberOfLines = 0
        label.text = meeting
        return label
    }
}

Custom Cell Xib:

enter image description here

Output in simulator:

enter image description here

Hope this helps.

Upvotes: 2

Related Questions