使って創ってApp

ソフトウェアを使ったり作ったりするブログです

iOSアプリ開発でUITableViewCellのCustomCellを作成する

iOSアプリ開発で、UITableViewCell の CustomCell を作成する方法を紹介します。UITableViewCell のサブクラスと xibファイルを作って、UITableView で使います。

開発環境

完成予定図

f:id:hitxutokun:20160112221542p:plain

上図の UITableViewCell のサブクラスとxibファイルを UITableView に表示します。

f:id:hitxutokun:20160112225057p:plain

CustomCell を10個表示しました。

UITableView で CustomCellを使う

  1. UITableViewCell のサブクラスと、xibファイルを作成する

    新規 Cocoa Touch Class ファイルを作成します。

    ファイルの設定
    • Subclass of: UITableViewCell
    • Also create XIB file にチェックをつける

    f:id:hitxutokun:20160112220449p:plain

  2. xibファイルを編集

    見た目を作ります。

    f:id:hitxutokun:20160112221542p:plain

    Cell に identifer を設定します。右側の Attributes inspector 画面で設定します。CustomCell にしました。

    f:id:hitxutokun:20160112221841p:plain

    Cell と 先ほど作った UITableViewCell のサブクラスは自動的に関連付けられているので、UIView Object に Outlet を接続することができます。今回はやりませんが。

  3. TableViewControllerを設定

    tableView に先ほど編集したxibファイルを関連付けます。viewDidLoad メソッド内に以下のコードを書きます。

    let nib = UINib(nibName: "CustomCell", bundle: NSBundle.mainBundle())
    self.tableView.registerNib(nib, forCellReuseIdentifier: "CustomCell")

    あとは普段 UITableViewController を使うように Cell を表示させます。

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
      return cell
    }

    Cell を呼び出す際、as! CustomCell と書いて CustomCell クラスにダウンキャストさせています。

    これで完成です!

    f:id:hitxutokun:20160112225057p:plain