LoginSignup
31
25

More than 5 years have passed since last update.

【Swift4】UITableViewのミニマムサンプル【iOS】

Last updated at Posted at 2018-02-02

とりあえず下のコードをコピペしてビルドするだけで、図のようなテーブルが表示できます。

for Xcode version 9.2 beta / Swift4
iPhone_8_Plus_-_11_2.png

ViewController.swift

//
//  ViewController.swift
//

import UIKit

class ViewController: UIViewController {

    var tableView:UITableView!

    let data = [
        ["ピカチュウ", "コラッタ", "イーブイ", "カビゴン", "ポッポ"],
        ["シナモロール", "モカ"]
    ]

    let sectionName = ["ポケモン","サンリオ"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // テーブルのインスタンス
        tableView = UITableView()

        // テーブルサイズを画面いっぱいに
        tableView.frame = view.frame

        // デリゲート
        tableView.delegate = self
        tableView.dataSource = self

        // セルをテーブルに紐付ける
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        // データのないセルを表示しないようにするハック
        tableView.tableFooterView = UIView(frame: .zero)

        // テーブルを表示
        view.addSubview(tableView)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

// データ・ソース
extension ViewController: UITableViewDataSource {

    // セクションごとにデータ要素数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[section].count
    }

    // セクション数
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionName.count
    }

    // セクションヘッダ
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?  {
        return sectionName[section]
    }

    // セルの高さ
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }

    // セル生成
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = data[indexPath.section][indexPath.row]
        cell.accessoryType = .disclosureIndicator
        //cell.accessoryView = UISwitch() // スィッチ

        return cell
    }
}

// セルタップ時の動作定義など
extension ViewController: UITableViewDelegate {

    // セクションヘッダの高さ
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

    // セルタップ時の挙動
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)
    }
}

その他のミニマムサンプルシリーズ
【Swift4】WKWebViewのミニマムサンプル【iOS】
【Swift4】UIProgressViewのミニマムサンプル【iOS】

31
25
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
31
25