问题描述
在 SwiftUI 中,您可以将多个视图作为一个参数传递给另一个视图,这要归功于 @ViewBuilder
.每个子视图都是单独处理的,因此在传递后,可以包含在 VStack
、HStack
等中
In SwiftUI you are able to pass multiple views as one parameter to another view, thanks to @ViewBuilder
. Each child view is treated individually, and so after being passed, can be contained in a VStack
, HStack
etc.
我的问题是:这个容器视图是否可以单独修改传递给它的每个子视图?例如,通过在每个子视图之间添加一个 Spacer
.
My question is: is it possible for this container view to individually modify each child view passed to it? For example, by adding a Spacer
between each child view.
这是我正在寻找的等效功能:
Here is the equivalent functionality I'm looking for:
struct SomeContainerView<Content: View> {
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content()
}
let content: Content
var body: some View {
HStack {
ForEach(content.childViews, id: \.id) { child in
// Give each child view a background
// Add a Spacer in between each child view
// Conditional formatting
// Etc.
}
}
}
}
我相信这是可能的,因为标准的 SwiftUI 容器视图可以影响传递给它们的子视图的外观和布局.除非这是通过 SwiftUI 的内部功能实现的?
I believe this to be possible as standard SwiftUI container views can influence the appearance and layout of child views passed to them. Unless this is achieved though internal features of SwiftUI?
解决这个问题的一种方法可能是传入多个视图参数而不是一个,尽管如果需要传递多个视图,这是不灵活和混乱的.一组视图似乎也没有意义,因为我在 SwiftUI 中的任何地方都没有注意到这种模式.
A way around this may be to pass in multiple view parameters instead of one, though this is inflexible and messy if many views need to be passed. An array of views doesn't seem to make sense either, as I have not noticed this pattern anywhere in SwiftUI.
推荐答案
据我所知,你不能做这样的事情.但是您可以使用数组 View 并遍历该视图并修改您的子视图.
As per my knowledge, You can not do something like this. But you can use the array View and iterate over the view and modify your child view.
这是演示:
struct SomeModel<Content: View>: Identifiable {
var body: Content
var id = UUID()
}
public struct SomeContainerView<Content: View>: View {
let items: [SomeModel<Content>]
init(items: [SomeModel<Content>]) {
self.items = items
}
public var body: some View {
HStack {
ForEach(items.indices) { index in
items[index].body.background(index % 2 == 0 ? Color.red : Color.green)
}
}
}
}
struct TestSomeView: View {
var body: some View {
SomeContainerView(items: [.init(body: Text("Child_view_1")),
.init(body: Text("Child_view_2")),
.init(body: Text("Child_view_3"))])
}
}
这篇关于在 SwiftUI 中使用 @ViewBuilder 单独修改传递给容器的子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!