2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift5でTableViewを使う方法

Last updated at Posted at 2020-04-07

はじめに

今回はTableViewを使います。※端折って書いちゃいます。
「Xib」を使ってカスタムなセルを作成することもできますが、まずは簡単なストーリーボードの「Table View cell」でてっとり早く実装したいと思います。

環境

Xocde10.2
swift5

実装

コード

まずはコードを書きます。

test.swift
import UIKit

class TestPage: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    //cellに表示するデータ
    let testList = ["Test1", "Test2", "Test3"]
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    //セルの数を指定
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return testList.count
    }
    
    //セルに値を設定
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // セルを取得する
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        // セルに表示する値を設定する
        cell.textLabel!.text = testList[indexPath.row]
        return cell
    }
}

ストーリーボードをいじる

「ライブラリ」から「Table View」,「Table View cell」を自分の配置したい画面に挿入します。
スクリーンショット 2020-04-07 16.12.22.png

下記のようになります。
スクリーンショット 2020-04-07 16.10.07.png

「show the Attributes inspector」から「Identifier」に「cell」を入力します。
スクリーンショット 2020-04-07 16.15.59.png

終わりに

今回はTable Viewの簡単な使い方をお話しました。
よく見る一般的なTableViewはこれで大丈夫ですが、UI/UXを気にしたレイアウトなどではやはり「Xib」を使ったカスタムセルがお勧めです。まずは基本からこういったもので簡単に実装できるということを知りステップアップでカスタムセルを自作するのもいいと思います。

2
3
2

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?