我如何创建自己的控件,如下所示
StripedTable(colors: [Color.blue, Color.red]) {
HStack { ... }
Text()
Whatverer()
}
,它将蓝色背景应用于HStack
和Whatever
,红色背景应用于Text
。
答案 0 :(得分:1)
检查一下:
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")
})
}
}
}
}
结果:
答案 1 :(得分:1)
我无需使用辅助函数遍历索引就可以使用它。不确定这是否比 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)])
}
}
}
}
答案 2 :(得分:0)
我认为您无法通过手动编码表中的每个项目来做到这一点,我最终所做的事情是这样的:
ScrollView {
ForEach(0..<itemList.count, id: \.self) { idx in
MyItem(index: idx, item: itemList[idx])
}
}
然后在您的物品上
var body: some View {
HStack {
// Some component code
}.backgroundColor(index % 2 == 0 ? Color.blue : Color.red)
}