如何在SwiftUI中将通用视图传递给结构

时间:2020-10-08 12:11:50

标签: swift swiftui

对于以下代码,我收到错误Failed to produce diagnostic for expression; please file a bug report。在我看来,这很简单,但可能与泛型有关。如何将通用视图传递给结构?

在SwiftUI视图中,我有这个:

import SwiftUI

struct PageView<Page: View>: View {
    var views: [UIHostingController<Page>]

    init(_ views: [Page]) {
        self.views = views.map { UIHostingController(rootView: $0) }
    }

    var body: some View {
        Text("Page View")
    }
}

struct View1: View {
    var body: some View {
        Text("View 1")
    }
}

struct View2: View {
    var body: some View {
        Text("View 2")
    }
}

struct Reference: View {
    var body: some View {             // <- Error here
        PageView([View1(), View2()])
    }
}

1 个答案:

答案 0 :(得分:2)

这是可能的解决方法

struct Reference: View {
    var body: some View {             
        PageView([AnyView(View1()), AnyView(View2())])
    }
}