UITableViewControllerを使うと嬉しいこと
2つのメリット
-
Static Cell
が使えること - 入力欄をタップしてキーボードが表示された際、入力欄が隠れないよう、自動的にスクロールしてくれる点
Static Cellって?
- 静的にセクションやセルの数を指定するもの
- 設定画面など、単純なTableViewを使った画面を作りたいときに、サクッと作れて便利
- 普通の
UITableView
ではStatic Cell
は使えず、指定してもコンパイルエラーになる
入力欄のスクロール制御
-
UIScrollView
の中に入力欄を設置した場合、キーボードが表示されてもスクロール制御はされず、入力欄が隠れてしまうことがある- 入力欄が隠れないようにするためには、コード側でちょっとややこしいスクロール制御を加える必要がある


-
UITableViewController
の中に入力欄を設置した場合、キーボードを開いても入力欄が隠れないように自動制御してくれるため、コード側での指定が不要で、とても簡単


Static Cell を使った入力画面の作成手順
準備
- プロジェクトを
Single View App
で作成 -
ViewController.swift
のUIViewController
をUITableViewController
に変更
import UIKit
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Main.storyboard
- Storyboard上に
Table View Controller
を設置

-
Storyboard Entry Point
を追加したTable View Controller
に変更 -
Identify Inspector
パネルのCustom Class
>Class
欄に、ViewController
を入力

-
Attributes Inspector
パネルの最上部にあるContent
をStatic Cell
に変更

-
Sections
の部分で、必要なセクション数に変更 (今回は5
)



-
Table View Cell
の中にText Field
を設置し、上下左右にConstraints
を加える (今回は全て0
)


備考
最初から UITableViewController でswiftファイルを作成した場合
- Static Cell にすることで不要となる
numberOfSections(in tableView: UITableView)
とtableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
を削除

環境
- Xcode Version 9.4.1