swift - 在 UITableView 中使用 CustomStringConvertible

标签 swift uitableview customstringconvertible

我已经声明了以下内容:

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")
]

我想将此信息输入到 UITableView 中,特别是在 tableView:cellForRowAtIndexPath: 中。

例如:

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

我该怎么做?我想不通。

非常感谢!

最佳答案

首先,您的 Controller 必须实现 UITableViewDataSource。 然后,

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
}

关于swift - 在 UITableView 中使用 CustomStringConvertible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44871048/

相关文章:

java - 没有收到来自 firebase 的推送通知但是使用 Pusher 应用程序

ios - 错误 - EXC_BREAKPOINT(代码=1,子代码=0x100308448)

swift - 在 Kitura 中运行单元测试时出错

ios - 分组的 UITableView - 复制设置应用 TableView

swift - 有没有一种方法可以根据参数类型简化这个 'matrix of overloads',这些参数类型最终都可以由特定类型表示?

ios - 如何验证自定义 Eureka 行中的文本字段等对象?

ios - 双击 UITableview 中的单元格以执行 segue

swift - 普通 View Controller 中的 UITableView 未使用我的自定义单元格进行更新

swift - 我什么时候以及为什么要在 Swift 中使用协议(protocol)?