2017-07-02 36 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類型。