はじめに
タイトルのとおりですが、ヘッダ・フッタを追加したいことなどもあると思うので、UIViewController を継承したクラスを使っています。
イメージ
アイテムの作成
TableView に表示するアイテムを作ります。
Item.swift
import Foundation
struct Item{
var title: String
var subtitle: String
init (title: String, subtitle: String) {
self.title = title
self.subtitle = subtitle
}
}
カスタムセル
カスタムセルを作成します。流れはざっと以下の通りです。
- Storyboard 上で各種 View を配置する
- Storyboard 上で制約をつける
- CustomCell クラスを作成する
- ユーティリティ画面の Custom Class を「CustomCell」とする
- Table View Cell の Identifier を「Cell」とする
- 更新対象の View を CustomCell と紐付ける
尚、ラベルについては、複数行・改行位置対応のため、ユーティリティ画面から Lines を「0」、Line Breaks を「Word Wrap」とします。
CustomCell
import UIKit
import Foundation
class CustomCell: UITableViewCell {
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelSubtitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Table View
下記対応をします。
- 親 View に対して、上下左右の制約を設定する
- Table View を ViewController と紐付ける
ViewController
ViewController はこんな感じです。高さ調整は下記一行でオッケーのようです。
self.tableView.rowHeight = UITableViewAutomaticDimension
ViewController
import UIKit
import Foundation
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var items = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
self.items.append(Item(title: "タイトル1", subtitle: "サブタイトル1"))
self.items.append(Item(title: "タイトル2", subtitle: "改行が表示されるようにちょっと長めの文字を入れる"))
self.tableView.rowHeight = UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomCell
cell.labelTitle.text = items[indexPath.row].title
cell.labelSubtitle.text = items[indexPath.row].subtitle
return cell
}
}