Nas*_*sir 6 struct ios swift-protocols swiftui viewbuilder
我的好奇心促使我将View类型作为参数传递给@ViewBuilder. 将模型/基元类型作为参数传递@ViewBuilder是完全有效的。
如下代码所示。
struct TestView<Content: View>: View {
let content: (String) -> Content
init(@ViewBuilder content: @escaping (String) -> Content) {
self.content = content
}
var body: some View {
content("Some text")
}
}
struct ContentTestView: View {
var body: some View {
TestView {
Text("\($0)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
代替String在
let content: (String) -> Content
Run Code Online (Sandbox Code Playgroud)
如果我尝试传递 SwiftUIView类型,则编译器对此不满意。
let content: (View) -> Content
Run Code Online (Sandbox Code Playgroud)
尽管 params for@ViewBuilder接受自定义协议类型Searchable,但不接受View协议。
编译器告诉我这个Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
我的整个想法是content可以保留Section/List/Text它。
编辑:我期望的代码如下所示。
struct TestView<Content: View>: View {
let content: (View) -> Content
init(@ViewBuilder content: @escaping (View) -> Content) {
self.content = content
}
var body: some View {
content(
List {
ForEach(0..<10) { i in
Text(\(i))
}
}
)
}
}
struct ContentTestView: View {
var body: some View {
TestView { viewbody -> _ in
Section(header: Text("Header goes here")) {
viewbody
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有什么办法可以实现这个目标吗?
可能的解决方案是使用AnyView,例如
struct TestView<Content: View>: View {
let content: (AnyView) -> Content
init(@ViewBuilder content: @escaping (AnyView) -> Content) {
self.content = content
}
var body: some View {
content(AnyView(
Text("Demo") // << put here any view hierarchy
))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4672 次 |
| 最近记录: |