2017-07-02 38 views
1

我已经声明使用CustomStringConvertible如下:在UITableView的

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

我会怎么做呢?我无法弄清楚。

非常感谢!

回答

0

首先,你的控制器必须实现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 
} 
0

我想你可能会混淆CustomStringConvertible与其他一些设计模式。首先,一个答案:

// You have some container class with your tableView methods 
class YourTableViewControllerClass: UIViewController { 

    // You should probably maintain your songs array in here, making it global is a little risky 

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

     // Get the song at the row 
     let cellSong = songs[indexPath.row] 

     // Use the song 
     cell.titleLabel.text = cellSong.title 
     cell.artistLabel.text = cellSong.artist 
    } 
} 

由于电池的标题/艺术家已经是公开的字符串,你可以根据需要使用它们。 CustomStringConvertible将允许您使用作为字符串的实际对象本身。所以,就你的情况而言,你可以有一个song并呼叫song.description,它会打印出“标题艺术家”。但是,如果您想要使用歌曲的titleartist,则应该拨打song.titlesong.artistHere's the documentation on that protocol.

另外,正如我上面写的,尝试将songs数组移动到您的ViewController中。也许考虑使用struct s而不是class s为您的Song类型。