SwiftUI中具有交替行颜色的表格

SwiftUI中具有交替行颜色的表格,swiftui,Swiftui,我如何创建自己的控件,其工作方式如下 StripedTable(colors: [Color.blue, Color.red]) { HStack { ... } Text() Whatverer() } 它会将蓝色背景应用于HStack和无论什么,将红色背景应用于文本我不认为您可以通过手动编码表中的每个项目来实现这一点,我最后所做的是: 滚动视图{ ForEach(0..查看以下内容: struct StripedTable<Content, Content2&

我如何创建自己的控件,其工作方式如下

StripedTable(colors: [Color.blue, Color.red]) {
    HStack { ... }
    Text()
    Whatverer()
}

它会将蓝色背景应用于
HStack
无论什么
,将红色背景应用于
文本

我不认为您可以通过手动编码表中的每个项目来实现这一点,我最后所做的是:

滚动视图{
ForEach(0..查看以下内容:

struct StripedTable<Content, Content2> : View where Content: View, Content2: View {

    var content: Content
    var content2: Content2

    var colors: [Color]

    public init(colors: [Color], @ViewBuilder content: () -> Content, @ViewBuilder content2: () -> Content2) {
        self.colors = colors
        self.content = content()
        self.content2 = content2()
    }
    var body: some View {
        VStack {
            content.background(colors[0])
            content2.background(colors[1])
        }
    }
}


struct ContentView: View {
    var body: some View {
        VStack {
            ForEach(UIFont.familyNames, id: \.self) { index in
                StripedTable(colors: [Color.blue, Color.red], content: {
                    HStack {
                        Text("just")
                        Text("a")
                        Text("test")
                    }
                },content2: {
                    Text("in red")
                })
            }
        }
    }
}
struct StripedTable:View其中Content:View,Content2:View{
var-content:content
var content2:content2
变量颜色:[颜色]
public init(颜色:[Color],@ViewBuilder content:()->content,@ViewBuilder content2:()->content2){
self.colors=颜色
self.content=content()
self.content2=content2()
}
var body:一些观点{
VStack{
content.background(颜色[0])
内容2.背景(颜色[1])
}
}
}
结构ContentView:View{
var body:一些观点{
VStack{
ForEach(UIFont.familyNames,id:\.self){中的索引
可条带化(颜色:[颜色.蓝色,颜色.红色],内容:{
HStack{
文本(“公正”)
文本(“a”)
文本(“测试”)
}
},内容2:{
文本(“红色”)
})
}
}
}
}
结果:


我不需要使用辅助函数遍历索引就可以使用它。不确定这是否比Oscar Franco的回答好,但与他的回答一样,它将使用奇数个元素:

struct Alternating: View {
    var backgroundColors = [
        Color.red,
        Color.blue,
    ]
    var dummyValues = ["One", "Two", "Three", "Four", "Five"]

    func nextBackgroundIndex(_ index: inout Int) -> Int {
        index = index + 1
        return index % 2
    }
    var body: some View {
        var index = 0
        VStack {
            ForEach(dummyValues, id: \.self) { dummyValue in
                Text(dummyValue)
                    .frame(maxWidth: .infinity)
                    .background(backgroundColors[nextBackgroundIndex(&index)])
            }
        }
    }
}

有趣的方法