Home > Software design >  How to pass view of different type to another view in SwiftUI?
How to pass view of different type to another view in SwiftUI?

Time:11-27

So I have this TestView which accepts headerContent and bodyContent,

struct TestView<Content: View>: View {
  var headerContent: (() -> Content)?  = nil
  let bodyContent: () -> Content
  
  var body: some View {

    VStack {
      headerContent?()
      bodyContent()
    }
  }
}

And I use it as,

struct ContentView: View {  
  var body: some View {
    TestView(headerContent: {
      Text("HeaderContent")
    }) {
      ScrollView {

      }
    }
  }
}

But I get the following error,

Cannot convert value of type 'ScrollView<EmptyView>' to closure result type 'Text'

What am I missing?

CodePudding user response:

You need to have two View generics, since headerContent and bodyContent are not the same.

Without this, you are saying there is some concrete type Content that conforms to View. However, both Text and ScrollView are different types, not the same.

Code:

struct TestView<HeaderContent: View, BodyContent: View>: View {
    var headerContent: (() -> HeaderContent)? = nil
    let bodyContent: () -> BodyContent

    var body: some View {
        VStack {
            headerContent?()
            bodyContent()
        }
    }
}
  • Related