iOSアプリ開発でUITableViewCellのCustomCellを作成する
iOSアプリ開発で、UITableViewCell の CustomCell を作成する方法を紹介します。UITableViewCell のサブクラスと xibファイルを作って、UITableView で使います。
開発環境
完成予定図
上図の UITableViewCell のサブクラスとxibファイルを UITableView に表示します。
CustomCell を10個表示しました。
UITableView で CustomCellを使う
-
UITableViewCell のサブクラスと、xibファイルを作成する
新規 Cocoa Touch Class ファイルを作成します。
- ファイルの設定
-
- Subclass of: UITableViewCell
- Also create XIB file にチェックをつける
-
xibファイルを編集
見た目を作ります。
Cell に identifer を設定します。右側の Attributes inspector 画面で設定します。CustomCell にしました。
Cell と 先ほど作った UITableViewCell のサブクラスは自動的に関連付けられているので、UIView Object に Outlet を接続することができます。今回はやりませんが。
-
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 クラスにダウンキャストさせています。
これで完成です!