🧩 XIBとは?

XIB(.xibファイル)は、Interface Builder(IB)を使ってUIを定義するXML形式のファイルです。Storyboardのように画面全体ではなく、部品単位で再利用可能なUIコンポーネントを作成するのに適しています。


…読み込み中…

🧱 基本構造と目的

🛠 XIBの作り方

  1. Xcodeで「File > New > File…」
  2. 「User Interface」→「View」や「Table View Cell」などを選択
  3. クラス名と同じ名前のXIBを作ると連携がスムーズ

🔗 XIBとクラスの接続

Interface Builderでクラスを指定し、IBOutletIBActionで紐づけます。

class CustomView: UIView {
  @IBOutlet weak var titleLabel: UILabel!

  required init?(coder: NSCoder) {
    super.init(coder: coder)
    commonInit()
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    commonInit()
  }

  private func commonInit() {
    Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
    addSubview(titleLabel.superview!)
  }
}

📦 UITableViewCell / UICollectionViewCell にXIBを使う

// 登録
tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "cell")

// 使用
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

Storyboardを使わずに動的にセルやビューを作りたいときに便利です。

✅ XIBを使うメリット

⚠️ 注意点

🔗 参考リンク