gpt4 book ai didi

ios - SwiftUI,在@Viewbuilder 中将 View 作为参数传递

转载 作者:行者123 更新时间:2023-12-05 06:10:41 28 4
gpt4 key购买 nike

出于好奇,我将 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)")
}
}
}

代替String

let content: (String) -> Content

如果我尝试传递一个 SwiftUI View 类型,那么编译器会对此不满意。

let content: (View) -> Content

即使 @ViewBuilder 的参数接受自定义协议(protocol)类型,如 Searchable 但不接受 View 协议(protocol)。

编译器告诉我这个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
}
}
}
}

有什么方法可以实现这一点?

最佳答案

可能的解决方案是使用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
))
}
}

关于ios - SwiftUI,在@Viewbuilder 中将 View 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64351885/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com