0

I made a class named ViewController which is an UICollectionViewController. I wanted to implement it in ContentView which is a View.

I tried using UIViewControllerRepresentable protocol, but I got error. In addition, I went through the SwiftUI tutorial made by Apple, but could not solve the problem.

import SwiftUI

struct ViewControllerWrapper: UIViewControllerRepresentable {

    func makeUIViewController(context: Context) -> ViewController {
        let vc = ViewController()
        return vc
    }

    func updateUIViewController(_ uiViewController: ViewController, context: Context) {

    }

}

struct ContentView : View {
    var body: some View {
        ViewControllerWrapper()
    }
}
Maric Vikike
  • 237
  • 2
  • 8

1 Answers1

3

You'll want to start by successfully initializing a UICollectionViewController. Only doing UICollectionViewController() will not work. So you can use something like this:

import SwiftUI

struct CollectionView: UIViewControllerRepresentable {

    func makeUIViewController(context: Context) -> UICollectionViewController {
        let vc = UICollectionViewController(collectionViewLayout: UICollectionViewLayout())
        return vc
    }

    func updateUIViewController(_ uiViewController: UICollectionViewController, context: Context) {
        //
    }
}

#if DEBUG
struct CollectionView_Previews: PreviewProvider {
    static var previews: some View {
        CollectionView()
    }
}
#endif
MScottWaller
  • 3,321
  • 2
  • 24
  • 47