0
0

More than 3 years have passed since last update.

Swiftでtableviewを使う(基礎)

Posted at

はじめに

Swiftでtableviewを使った開発をします。
簡単な使い方とそれぞれの特有の関数の説明をします。

TableViewとは

配列などで格納されたデータをリストのようにして出力したい時に使います。
チャット機能や商品の一覧など応用パターンが多いのが特徴になります。
今回は配列に入っているいくつかの要素をリストにして出力してみます。

特有のメソッド

numberOfRowsInSection

セルの数を決めるメソッド

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return セルの数
}

numberOfSections

セルのセクション数を決めるメソッド

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

cellForRowAt

セルを構築する際に使うメソッド

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return cell
}

heightForRowAt

セルの高さを指定するメソッド

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return view.frame.size.height/6
}

didSelectRowAt

セルがタップされた時に呼び出されるメソッド

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

簡単な使い方

①プロジェクトを立ち上げる

②main.storyboardでTableViewを配置する
スクリーンショット 2021-01-09 14.31.01.png
スクリーンショット 2021-01-09 14.31.21.png
上の画像のようにTableViewのパーツを端に合わせる(AutoLayout使っても可)

③セルとなるxibファイルを作成する
TableView → CocoaTouchClass → 画像のようにSubbClass ofを変更
今回はTableViewCellという名前のファイルを作成しています。
スクリーンショット 2021-02-28 14.52.14.png

④xibファイルを変更する
1.TableViewCell.xibでLabelを配置する。
2.配置したLabelをTableView.swiftに紐付ける。
3.画像右上のidentifierにcellと入力。
スクリーンショット 2021-02-28 17.11.35.png

⑤ViewController.swiftを変更する

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let array = ["グレープ", "レモン", "アップル", "メロン"] //表示される配列を準備

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        //使うセルを指定する
        tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")  

    }

    //TableViewに貼り付ける要素を指定する
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return array.count

    }

    //cellを設定する
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

        cell.label.text = array[indexPath.row]

        return cell

    }

}

最後に

簡単あ使い方のみの説明となりました。
チャット機能のものからもっと高度な使い方までできるので、自分で作りたいものをでリストっぽいものが欲しいなと思ったら使ってみてください。

参照

0
0
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
0
0