LoginSignup
16
16

More than 5 years have passed since last update.

[iOS] 敢えてTableViewControllerにする2つの嬉しいこと

Posted at

UITableViewControllerを使うと嬉しいこと

2つのメリット

  1. Static Cell が使えること
  2. 入力欄をタップしてキーボードが表示された際、入力欄が隠れないよう、自動的にスクロールしてくれる点

Static Cellって?

  • 静的にセクションやセルの数を指定するもの
  • 設定画面など、単純なTableViewを使った画面を作りたいときに、サクッと作れて便利
  • 普通の UITableView では Static Cell は使えず、指定してもコンパイルエラーになる

入力欄のスクロール制御

  • UIScrollView の中に入力欄を設置した場合、キーボードが表示されてもスクロール制御はされず、入力欄が隠れてしまうことがある
    • 入力欄が隠れないようにするためには、コード側でちょっとややこしいスクロール制御を加える必要がある

Simulator Screen Shot - iPhone SE - 2018-07-06 at 06.10.03.png

Simulator Screen Shot - iPhone SE - 2018-07-06 at 06.10.17.png

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

Simulator Screen Shot - iPhone SE - 2018-07-06 at 06.10.03.png

Simulator Screen Shot - iPhone SE - 2018-07-06 at 06.10.12.png

Static Cell を使った入力画面の作成手順

準備

  • プロジェクトを Single View App で作成
  • ViewController.swiftUIViewControllerUITableViewController に変更
import UIKit

class ViewController: UITableViewController {

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

}

Main.storyboard

  • Storyboard上に Table View Controller を設置

スクリーンショット 2018-07-06 6.36.05.png

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

スクリーンショット 2018-07-06 6.35.20.png

  • Attributes Inspector パネルの最上部にある ContentStatic Cell に変更

スクリーンショット 2018-07-06 5.27.11.png

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

スクリーンショット 2018-07-06 6.37.51.png

スクリーンショット 2018-07-06 5.38.56.png
- Document Outline パネルから Table View Section を選択し、 Attributes Inspector パネル の Rows 欄でCell数を指定し、 Header 欄でセクションのタイトルを指定

スクリーンショット 2018-07-06 6.39.29.png

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

スクリーンショット 2018-07-06 6.08.59.png

Simulator Screen Shot - iPhone SE - 2018-07-06 at 06.10.03.png

備考

最初から UITableViewController でswiftファイルを作成した場合

  • Static Cell にすることで不要となる numberOfSections(in tableView: UITableView)tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) を削除

スクリーンショット 2018-07-06 5.55.41.png

環境

  • Xcode Version 9.4.1
16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16