简体   繁体   English

如何将不同类型的视图传递给 SwiftUI 中的另一个视图?

[英]How to pass view of different type to another view in SwiftUI?

So I have this TestView which accepts headerContent and bodyContent ,所以我有这个接受headerContentbodyContentTestView

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?我错过了什么?

You need to have two View generics, since headerContent and bodyContent are not the same.你需要有两个View generics,因为headerContentbodyContent不一样。

Without this, you are saying there is some concrete type Content that conforms to View .没有这个,你说的是有一些符合View的具体类型Content However, both Text and ScrollView are different types, not the same.但是, TextScrollView都是不同的类型,并不相同。

Code:代码:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将可选视图传递给 SwiftUI 中的另一个视图? - How to pass optional view to another view in SwiftUI? SwiftUI - 如何将 Date() 作为字符串传递给另一个视图? - SwiftUI - How to pass Date() as a string to another view? 如何将一个 SwiftUI 视图作为变量传递给另一个视图结构 - How to pass one SwiftUI View as a variable to another View struct SwiftUI:如何将视图作为参数传递给另一个视图以获取底部工作表? - SwiftUI: How to pass a View as a parameter into another View to get Bottom Sheet? 如何将数据从一个视图传递到 SwiftUI 中的另一个视图? - How to pass data from a view to another view in SwiftUI? 如何从另一个视图传递字段文本值 swiftui - How to pass a fieldtext value from view another view swiftui 如何将 SwiftUI 中的 static 值从一个视图传递到另一个视图? - How to pass static values in SwiftUI from one View to another? 如何将不同的获取请求传递给 SwiftUI 中的一个视图 - How to pass different fetch requests to one view in SwiftUI 如何将 AsyncImage object 的返回图像传递给 SwiftUI 中的不同视图? - How to pass the returned Image of an AsyncImage object to a different view in SwiftUI? Swift/SwiftUI – 将数组传递给另一个视图 - Swift/SwiftUI – Pass array to another view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM