LoginSignup
12
13

More than 5 years have passed since last update.

xib を使って再利用可能な View を作成する

Posted at

はじめに

xib を使って色々な画面で使いまわせる汎用的な View のつくり方を紹介します。

xib ファイルを作成する

File -> New -> File... (⌘ + N) からファイルを新規作成します。Cocoa Touch Class を選択して Next しましょう。

スクリーンショット 2018-01-24 20.12.55.png

名前は適当に CustomTableViewCell としておきます。
Also create XIB file にチェックをつけ Next をクリックし、任意のディレクトリに保存します。

スクリーンショット 2018-01-24 20.13.05.png

作成が完了すると CustomTableViewCell.xib と CustomTableViewCell.swift の二つが Project navigator に追加されます。

スクリーンショット 2018-01-24 19.55.24.png

xib を編集する

Storyboard と同じ要領で編集することが可能です。取り合えず今回は backgroundColor に Twitter カラーを指定してみます。
cell identifier (画像右上) も忘れずに設定しておきましょう。

スクリーンショット 2018-01-24 20.32.35.png

xib をコードから呼び出す

真っさらな何もない TableView に xib をセットしていきます。

スクリーンショット 2018-01-24 20.28.09.png

MainTableViewController
import UIKit

class MainTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // tableView に CustomTableViewCell を登録する
        self.tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil),
                                forCellReuseIdentifier: "customCell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // ここで CustomTableViewCell を呼び出す
        return self.tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell
    }
}

実行結果

以下が実行結果です。

IMG_0016.PNG

xib でヘッダーやボタンなどの View を作成しておくと色々な画面で使いまわすことができて便利ですね。

12
13
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
12
13