【Swift/UIKit】UIHostingConfigurationの使い方!UITableViewへSwift UIを組み込む
この記事からわかること
- Xcode/iOSでUIHostingConfigurationの使い方する
- Swift UIのViewをUIKitのUICollectionView / UITableViewに埋め込むには?
- UIHostingControllerとの違い
index
[open]
\ アプリをリリースしました /
環境
- Xcode:16.3
- iOS:18.4
- Swift:6
- macOS:Sequoia 15.4
Swift UIのViewをUIKitのViewControllerの中で使用する方法
Swift UIで構築したViewをUIKitのViewControllerで管理しているUI構造の中に埋め込むためには2つの方法があります。
- UIHostingControllerクラス・・・UIViewControllerへ変換する
- UIHostingConfigurationクラス・・・UIContentConfigurationへ変換する
UIHostingControllerクラス
UIHostingControllerはSwift UIのViewを主に画面単位で追加したい場合に使用されます。UIViewControllerへ変換することができるので、そのままSwift UIのViewを新規画面にしたり、パーツとして組み込んだりすることが可能です。
UIHostingConfigurationクラス
UIHostingConfigurationはSwift UIのViewを主にリストのセルなどで活用したい場合に使用されます。UIContentConfigurationへ変換することができるので、そUICollectionView / UITableViewと簡単に統合することが可能です。
UIHostingConfigurationの使い方
公式リファレンス:UIHostingConfiguration
public struct UIHostingConfiguration<Content, Background> : UIContentConfiguration where Content : View, Background : View
Swift UIで構築したViewをUIKitのUICollectionView / UITableViewで使用するためにはUIHostingConfigurationクラスを使用します。UIHostingConfiguration自体はWWDC22で発表された比較的あたらしい仕組みなのでiOS16以降でしか使用できません。ただ限定的ではありますが従来のUIHostingControllerよりもシンプルにViewを組み込むことができるようになっているのでUIKit => Swift UIへの移行にも大きく貢献してくれると思います。
使い方は簡単でcontentConfigurationプロパティにUIHostingConfigurationを格納するだけです。init(@ViewBuilder content: () -> Content)が用意されているのでSwift UIのViewをそのままインスタンス化して渡します。
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = items[indexPath.row]
// Swift UIのViewをインスタンス化して渡す
cell.contentConfiguration = UIHostingConfiguration {
RowView(title: item)
}
return cell
}
これでセルとして表示させたいViewをSwift UIで実装したUIで実装することが可能です。UITableViewやUITableViewControllerの使い方などは以下を参考にしてください。
class ViewController: UITableViewController {
private let items = ["りんご", "みかん", "バナナ", "ぶどう", "メロン"]
override func viewDidLoad() {
super.viewDidLoad()
title = "UIHostingConfiguration サンプル"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
items.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = items[indexPath.row]
cell.contentConfiguration = UIHostingConfiguration {
RowView(title: item)
}
return cell
}
}
struct RowView: View {
let title: String
var body: some View {
HStack {
Image(systemName: "star.fill")
.foregroundColor(.yellow)
Text(title)
.font(.headline)
Spacer()
}
.padding()
.background(Color(UIColor.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。
ご覧いただきありがとうございました。







