#author("2016-05-30T14:40:11+09:00","default:wikiwriter","wikiwriter")
[[UIKit/テーブル]]

&tag(UIKit/テーブル/セルの再利用);
*目次 [#mc083a7a]
#contents
*関連ページ [#pa4b278b]
*参考情報 [#q80d681b]

*概要 [#zd79fab7]

-cellForRowAtIndexPathで毎回UITableViewCellを生成しているとパフォーマンス上の問題が発生する可能性あり。
-これを回避するための方法
-参考: [[iOS6 UITableViewのセルの再利用の方法が変わった | Developers.IO:http://dev.classmethod.jp/smartphone/iphone/ios6-uitableview/]]
-[[UITableViewのセルの使いまわしについて – Morizotter Blog:http://blog.morizotter.com/2013/12/24/uitableview-customcell-storyboard/]]

*iOS 6以降: registerClassとdequeueReusableCellWithIdentifier:forIndexPath:を使う [#qedb1143]
-以下のようにあらかじめregisterClassで登録する
#pre{{
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 素直にCellのインスタンスを生成することもできる。
//        let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
        cell.textLabel?.text = rows[indexPath.row]
        return cell
    }
}}


※ストーリーボードで設定したプロトタイプセルを利用する場合、registerClassを呼び出してはいけない。

* iOS 6より前: dequeueReusableCellWithIdentifierを使う [#s390e821]
-iOS 6以後でも使うことができる。CellのStyleを指定したい場合などまだ使いどころはありそう。
#pre{{
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("myCell")
        if (cell == nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myCell")
            
        }
        let theCell = cell!
        theCell.textLabel?.text = rows[indexPath.row]
        return theCell

    }
}}


*トラブルシューティング [#ycf7d5cb]

**reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'が発生 [#z9a077c2]
-メッセージ通りプロトタイプセルにidentifierが設定されていないせい。
-Table View ControllerのPrototype Cellsを選択し、Identity InspectorのIdentifierに"myCell"と設定する。




トップ   編集 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS