【问题标题】:How to show an UICollectionViewController inside SwiftUI using representable protocol?如何使用可表示协议在 SwiftUI 中显示 UICollectionViewController?
【发布时间】:2019-07-26 22:36:29
【问题描述】:

我创建了一个名为 ViewController 的类,它是一个 UICollectionViewController。我想在 ContentView 中实现它,这是一个视图。

我尝试使用 UIViewControllerRepresentable 协议,但出现错误。另外,我浏览了苹果制作的SwiftUI教程,但无法解决问题。

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

【问题讨论】:

    标签: ios swift xcode swiftui xcode11


    【解决方案1】:

    您首先要成功初始化 UICollectionViewController。只做UICollectionViewController() 是行不通的。所以你可以使用这样的东西:

    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
    

    【讨论】:

    • 这将提供一个空白的 UICollectionViewController,但它可以让事情开始:)
    猜你喜欢
    • 2017-06-02
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    相关资源
    最近更新 更多