LoginSignup
7
6

More than 3 years have passed since last update.

【Swift】xibを使ってUITableViewを実装する

Posted at

はじめに

UITableViewを使用する際にカスタムセルを.xibを使用して実装する方法について書きます。
xibを使用することでカスタムセルのcalss内の記述をStoryboardベースで実装することができます。

この記事でやること

UITableViewCellのxibにあるLabelのテキストを変更する
Simulator Screen Shot - iPhone 12 - 2021-01-11 at 02.00.41.png

実装

TableViewの追加

画面いっぱいにTableViewを追加します。
スクリーンショット 2021-01-11 2.03.14.png

xibファイルを作成

Cocoa Touch Classを選択し、
スクリーンショット 2021-01-11 2.05.40.png

UITableViewCellを選択、Also Create XIB fileにチェックを入れ、ファイルを作成する
スクリーンショット 2021-01-11 2.07.02.png

Labelの追加

CellにLabelを追加し、Outlet接続する
スクリーンショット 2021-01-11 2.16.03.png

TableViewを作成

TableViewとコードをOutlet接続し、extensionに一般的なTableViewのコード()を書きます
スクリーンショット 2021-01-11 2.16.51.png

ここで一般的なTableViewと違うのがRegisterを記述する点と

ViewController.swift
tableView.dataSource = self
tableView.delegate = self
// registerでxibをidentifierとして設定する
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")

ここで設定したidentifierを使用する点です。

ViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    cell.titleLabel?.text = "aaa"

    return cell
}

ビルドしてみる

これで冒頭の通りxibを使用してUITableViewCellのテキストを変更することができたかと思います。
もし参考になればLGTMくれると嬉しいです!

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