如何在視圖引數中foreach
這是我的代碼
CarouselView(itemHeight: 124, views: [
SliderItemView(),
SliderItemView(),
SliderItemView(),
])
我想迭代并回圈顯示 SliderItemView
uj5u.com熱心網友回復:
ForEach無法創建陣列。如果你想創建一個這些視圖的陣列,一種方法是[0..<3].map { _ in SliderItemView() }
uj5u.com熱心網友回復:
這里有 2 種方法可以解決您的問題:
struct ContentView: View {
var body: some View {
CustomViewV1(content: {
ForEach(0...2, id:\.self) { _ in Text("Hello, World!").foregroundColor(Color.blue) }
})
CustomViewV2(repeating: 3, content: { Text("Hello, World!").foregroundColor(Color.red) })
}
}
struct CustomViewV1<Content: View>: View {
@ViewBuilder let content: () -> Content
var body: some View {
return content()
}
}
struct CustomViewV2<Content: View>: View {
let repeating: Int
@ViewBuilder let content: () -> Content
var body: some View {
if (repeating >= 1) {
ForEach(1...repeating, id:\.self) { _ in
content()
}
}
}
}
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345358.html
