開発メモ

開発関係のメモをいろいろと。たぶん。

UITableViewに曲の情報を表示

動作を確認した環境

環境 情報
Xcode 6.3.2 (6D2105)
iOS 8.3
Swift 1.2
Date 2015/6/6

UITableViewに曲の情報を表示

プレイリストを表示するUITableViewを管理するためのクラスを作成。iOS開発の入門書だと、DelegateやDataSourceをViewControllerに持たせる形が多いけど、個人的にはバッサリ分離するほうが好み。

import UIKit

class PlaylistTableAdmin: NSObject, UITableViewDelegate, UITableViewDataSource {

    func setup(tableView: UITableView) {
        tableView.delegate = self
        tableView.dataSource = self
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return g_musicPlayer.playlist.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellId = "Cell"

        let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! UITableViewCell
        let item = g_musicPlayer.playlist[indexPath.row]

        cell.textLabel?.text = item.title
        cell.detailTextLabel?.text = "\(item.artist) - \(item.albumTitle)"

        return cell
    }

}

やってる内容はものすごく基本的なことなので、特に説明はいらないかと。

ViewController側での処理はこんな感じ。

class ViewController: UIViewController {

    /// プレイリストを表示するTableView
    @IBOutlet weak var playlistTable: UITableView!
    var playlistTableAdmin: PlaylistTableAdmin!

    override func viewDidLoad() {
        super.viewDidLoad()

        g_musicPlayer.updatePlaylist()
        g_musicPlayer.viewController = self

        updatePlayInfo()
        updatePlayState()

        // TableView管理用のクラスを生成&設定
        playlistTableAdmin = PlaylistTableAdmin()
        playlistTableAdmin.setup(playlistTable)
    }

    ※関係ない部分は省略
}

ここまで出来たところで実行すると、こんな感じになる。

f:id:see_ku:20150606112446p:plain

ミュージックプレイヤーらしくなってきたかな?

ソースコード

最終的なソースコードはこちら。

See_Ku / MusicPlayerTips — Bitbucket
https://bitbucket.org/See_Ku/musicplayertips

https://itunes.apple.com/jp/app/four-album-shuffle-arubamu/id866046150?mt=8&uo=4&at=10l8JW&ct=hatenablog