うちのいぬ Tech Blog

Tech Blog of Uchinoinu/My dog

Custom Cell を使って TableView をいい感じに実装する - 最初の一歩

はじめに

TableViewをいい感じに作りたいので、いい感じにカスタムしたいと思い、Custom Cellを扱ってみることにしました。

Swift幼稚園児の備忘録です。

手順

1. StoryboardでTableViewを設置

2. Prototype CellsにTitleとSubTitleのlabelを設置

ここで好きなようにレイアウトする

Screen Shot 2015-08-17 at 13.52.33.png

3. Tableに表示するDataModelを作成

ここでデータを管理します。 DBから読んでもいいし、直書きでもいいし、ここにまとめるとスッキリしていいかもしれないです。

import Foundation

class FooTableData {
    class FooTableDataModel : NSObject {
        var title: String
        var subTitle: String
    
        init(title: String, subTitle: String){
            self.title = title
            self.subTitle = subTitle
        }
    }
    let items = [
        FooTableDataModel(title: "title 1", subTitle: "subTitle 1"),
        FooTableDataModel(title: "title 2", subTitle: "subTitle 2"),
        FooTableDataModel(title: "title 3", subTitle: "subTitle 3"),
        FooTableDataModel(title: "title 4", subTitle: "subTitle 4")
    ]    
}

4. Custom Cellの作成

UITableViewCellのサブクラスを作成。

import UIKit

class FooTableViewCell: UITableViewCell {

    // これは後からStoryboardでOutlet接続するので、実際にはこのタイミングでこれらのコードは記載しません。
    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var subTitle: UILabel!
    // ここまで

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

5. TableViewControllerの作成

UITableViewControllerのサブクラス。

import UIKit

class FooTableViewController: UITableViewController {

    let ftd = FooTableData()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ->; Int {
        return ftd.items.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->; UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as FooTableViewCell // ここを忘れないように
        let item = ftd.places[indexPath.row]
        let title.text = item.title
        let subTitle.text = item.subTitle
        return cell
    }
}

6. cellのcustom classとidentifierを設定

custom class

  1. Storyboardで対象のTableViewの中のセルを選択。
  2. custom class欄から、classをFooTableViewCellを選択

identifier

  1. Table View Cell欄から、identifierをcellに設定。

7. titleとsubTitleのラベルからFooTableViewCellにOutlet接続して、IBOutletを作成。

8. ViewControllerのクラスを設定

  1. Storyboardで対象のTableViewのViewControllerを選択
  2. CustomClass欄から、classをFooTableViewControllerに設定。

References