【Swift/UIKit】UIHostingConfigurationの使い方!UITableViewへSwift UIを組み込む

【Swift/UIKit】UIHostingConfigurationの使い方!UITableViewへSwift UIを組み込む

この記事からわかること

  • Xcode/iOSUIHostingConfiguration使い方する
  • Swift UIViewUIKitUICollectionView / UITableView埋め込むには?
  • UIHostingControllerとの違い

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

環境

Swift UIのViewをUIKitのViewControllerの中で使用する方法

Swift UIで構築したViewをUIKitのViewController管理しているUI構造の中に埋め込むためには2つの方法があります。

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をUIKitUICollectionView / 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で実装することが可能です。UITableViewUITableViewControllerの使い方などは以下を参考にしてください。


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))
    }
}

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

Search Box

Sponsor

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index