gpt4 book ai didi

swiftui - 如何在 SwiftUI 中循环 View 构建器内容 subview

转载 作者:行者123 更新时间:2023-12-03 19:03:03 25 4
gpt4 key购买 nike

所以我试图创建一个 View ,它接受 viewBuilder 内容,循环内容的 View 并在每个 View 和另一个 View 之间添加分隔线

struct BoxWithDividerView<Content: View>: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack(alignment: .center, spacing: 0) {
// here

}
.background(Color.black)
.cornerRadius(14)
}
}
所以在我写“here”的地方,如果有意义的话,我想遍历内容的 View 。我将编写一个不起作用的代码,但它解释了我想要实现的目标:
ForEach(content.subviews) { view  in
view
Divider()
}
怎么做?

最佳答案

所以我最终做了这个

@_functionBuilder
struct UIViewFunctionBuilder {
static func buildBlock<V: View>(_ view: V) -> some View {
return view
}
static func buildBlock<A: View, B: View>(
_ viewA: A,
_ viewB: B
) -> some View {
return TupleView((viewA, Divider(), viewB))
}
}
然后我像这样使用了我的函数构建器
struct BoxWithDividerView<Content: View>: View {
let content: () -> Content
init(@UIViewFunctionBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack(spacing: 0.0) {
content()
}
.background(Color(UIColor.AdUp.carbonGrey))
.cornerRadius(14)
}
}
但问题是这只适用于最多 2 个表达式 View 。我将发布一个单独的问题,说明如何将数组传递给它

关于swiftui - 如何在 SwiftUI 中循环 View 构建器内容 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64238485/

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