Search code examples
swiftuitableviewcustomstringconvertible

Using CustomStringConvertible in UITableView


I've declared the following:

class Song: CustomStringConvertible {
    let title: String
    let artist: String

    init(title: String, artist: String) {
        self.title = title
        self.artist = artist
    }

    var description: String {
        return "\(title) \(artist)"
    }
}

var songs = [
    Song(title: "Song Title 3", artist: "Song Author 3"),
    Song(title: "Song Title 2", artist: "Song Author 2"),
    Song(title: "Song Title 1", artist: "Song Author 1")
]

I want to enter this information into a UITableView, specifically at the tableView:cellForRowAtIndexPath:.

Such as this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell

    cell.titleLabel = //the song title from the CustomStringConvertible[indexPath.row]
    cell.artistLabel = //the author title from the CustomStringConvertible[indexPath.row]
}

How would I do this? I can't figure it out.

Thanks a lot!


Solution

  • First, your Controller must implement UITableViewDataSource. Then,

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell
        cell.titleLabel?.text = songs[indexPath.row].title
        cell.artistLabel?.text =songs[indexPath.row].artiste
    }