🧱 基本構造と目的
- カスタムUIViewやUITableViewCell、UICollectionViewCellなどのUIパーツを再利用可能に
- Storyboardに比べて軽量で、モジュール化しやすい
- 動的に読み込み可能(プログラムでインスタンス化)
🛠 XIBの作り方
- Xcodeで「File > New > File…」
- 「User Interface」→「View」や「Table View Cell」などを選択
- クラス名と同じ名前のXIBを作ると連携がスムーズ
🔗 XIBとクラスの接続
Interface Builderでクラスを指定し、IBOutletやIBActionで紐づけます。
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を使うメリット
- UIコンポーネントの再利用性が高まる
- Storyboardよりも分割管理しやすく、チーム開発に向いている
- 動的生成がしやすい(Storyboardでは遷移が前提)
⚠️ 注意点
- XIBのファイル名とクラス名は一致させるのがベスト
- Auto Layoutの制約が不足しているとレイアウトが崩れる - 詳細
- 読み込みタイミングに注意(`awakeFromNib` vs `init`)