如何使用可表示协议在 SwiftUI 中显示 UICollectionViewController?
How to show an UICollectionViewController inside SwiftUI using representable protocol?
我创建了一个名为 ViewController 的 class,它是一个 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()
}
}
您首先要成功初始化 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
我创建了一个名为 ViewController 的 class,它是一个 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()
}
}
您首先要成功初始化 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