thecoolwinter
thecoolwinter

Reputation: 1002

Set Array of Strings in tableViewCell

I've got a tableViewCell that I need to have an array passed into the tableViewCell but not just passed into a text label or something like that. I'll let my code show.

My TableViewController:

let subjectsDict = ["Spanish": ["Lesson 1", "Lesson 2"], "Math":["Problem set 1", "Problem set 2"], "Science": ["Lab"]]

let subjectArray = ["Spanish", "Math", "Science"]

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

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "subjectCell", for: indexPath) as? SubjectTableViewCell else {
        return UITableViewCell()
    }

    cell.subjectList = subjectsDict[subjectArray[indexPath.row]]

    return cell
}

And my tableViewCell looks like this.

class subjectTableViewCell: UITableViewCell {
        var subjectList: [String] = []

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style , reuseIdentifier: reuseIdentifier)
        setUpTable()
    }
    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        setUpTable()
    }
    func setUpTable() {
        print(subjectList)
    }
        //other code for creating the cell
}

But when I print the subjectList from the subjectTableViewCell it prints none

Upvotes: 1

Views: 927

Answers (3)

Robert Dresler
Robert Dresler

Reputation: 11140

You're trying to print subjectList in the moment you initialise your table view cell so in this moment you haven't set subjectList yet. If you want to print subjectList you can do it after you set it.

After this line gets executed:

cell.subjectList = subjectsDict[subjectArray[indexPath.row]]

Upvotes: 0

rmaddy
rmaddy

Reputation: 318774

Your code makes no attempt to update the cell's content with the value of subjectList. All you show is a print.

Also note that your print is called before any attempt to set subjectList is made. And remember that cells get reused. setUpTable will only be called once but subjectList will be set over and over as the cell gets used.

The simplest solution is to update the cell when subjectList is set.

var subjectList: [String] = [] {
    didSet {
        textLabel?.text = subjectList.joined(separator: ", ")
    }
}

I'm assuming you are using the standard textLabel property. If you have your own label then update accordingly.

Upvotes: 1

D V
D V

Reputation: 348

If you just want to invoke setUpTable() when your subjectList in the cell gets updated, try using:

var subjectList: [String] = [] {
    didSet {
        setUpTable()
    }
}

Upvotes: 0

Related Questions