LoginSignup
1
2

UITableViewとUITableViewCellについて

Posted at

はじめに

配列でデータをリスト化するように画面配置したいときに使用するUITableViewですが、一緒にUITableViewCellも設定する必要があり、どういう役割の違いがあるか調べてみました。

UITableViewとUITableViewCellとは

・UITableViewは1つの表示する項目をセルという。
・このセルを使用するには、UITableViewCellを使用する。
・さらに、TableViewを使用するためには「delegate」「datasource」という機能を使用する必要がある。

#実際の使い方
① Main.storyboardから「UITableView」を配置
② 同様に「UITableViewCell」を画面に配置
③ Main.storyboardからdataSource、delegateを設定

「View Controller」のボタンまでcontrolボタンを押しながらドラッグ
スクリーンショット 2023-07-26 15.53.08.png

以下の通り、黒いポップアップが表示されるので、「dataSource」と「delegate」を選択
スクリーンショット 2023-07-26 15.55.58.png

「Table View Cell」を選択してideatifierという項目からセルの名称を指定
スクリーンショット 2023-07-26 15.57.23.png

今回は「HomeTweetCell」と命名

実装方法

TableViewに情報を表示するためにViewController.swiftを編集する。

TableViewをcontrolを押しながらTable Viewを選択し、ViewController.swiftへドラッグ。ポップアップ画面のNameに「TableView」と入力し、connectを押す。
スクリーンショット 2023-07-26 16.51.25.png

ViewController.swiftに以下のようにTable Viewの情報が追加される。

@IBOutlet weak var TableView: UITableView!

TableViewのDatasourceとDelegateを使用するため、extensionで以下のように追加。

extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
}

この中にUITableViewDelegateとUITableViewDataSourceメソッドを追加。

    /// データの数(=セルの数)を返すメソッド
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    /// 各セルの内容を返すメソッド
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()

これで、UITableViewによるデフォルトUITableViewCellができます。あとは、UITableViewに表示させたい内容のコードをここをベースに書いていくだけです。

まとめ

今回UITableViewとUITableViewCellの意味と実際の使い方についてまとめてみました。ご参考になればと思います。
・UITableViewは1つの表示する項目をセルのことをいう。
・このセルを使用するには、UITableViewCellを使用する。
・TableViewを使用するためには「delegate」「datasource」という機能を使用する必要がある。

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