2017-07-02 9 views
1

に私は次のことを宣言した:はの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") 
] 

私は、具体的tableView:cellForRowAtIndexPath:で、UITableViewにこの情報を入力します。このような

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.artistを呼び出すだけです。 Here's the documentation on that protocol.

また、上記のように、songsアレイをViewControllerに移動してみてください。 Songタイプではclassの代わりにstructを使用することをおすすめします。