如何在 swiftUI 的 Foreach 循环中显示除一项以外的图像?
How to display image except for one item on Foreach loop in swiftUI?
我创建了一张卡片,我希望在除第一张卡片之外的每张卡片顶部显示图像。请帮我解决这个问题。
这是保存图像的结构。
struct XButton: View {
var body: some View {
Image(systemName: "xmark")
.font(.system(size: 17, weight: .bold))
.foregroundColor(.white)
.padding(.all, 10)
.background(Color.black.opacity(0.6))
.mask(Circle())
}
}
这是在 foreach 循环中包含卡片的滚动视图
ScrollView{
ForEach(CardsData) { item in
VStack {
CardsView(Cards: item)
}
}
}
您可以在 ForEach
期间使用 enumerated()
获取索引 和 项。然后,XButton
仅在 index == 0
时有条件地呈现
然后,我使用 ZStack
将 XButton
放在最上面。我假设你原来的问题中的“在上面”意味着覆盖,但如果你只是意味着在 y 轴上更高,你可以将它改回 VStack
struct ContentView : View {
var body: some View {
ScrollView{
ForEach(Array(CardsData.enumerated()), id: \.1.id) { (index,item) in
ZStack {
CardsView(Cards: item)
if index == 0 {
XButton()
}
}
}
}
}
}
注意:这是假设 CardsData
项符合 Identifiable
,如果您的原始 ForEach
有效,我假设它们符合 Identifiable
。请注意,我从 .1.id
获取 ID,它是 CardsData
中项目的 id
属性,现在是一个元组,其中第一部分 (0) 是索引和第二个 (1) 是项目。
我创建了一张卡片,我希望在除第一张卡片之外的每张卡片顶部显示图像。请帮我解决这个问题。
这是保存图像的结构。
struct XButton: View {
var body: some View {
Image(systemName: "xmark")
.font(.system(size: 17, weight: .bold))
.foregroundColor(.white)
.padding(.all, 10)
.background(Color.black.opacity(0.6))
.mask(Circle())
}
}
这是在 foreach 循环中包含卡片的滚动视图
ScrollView{
ForEach(CardsData) { item in
VStack {
CardsView(Cards: item)
}
}
}
您可以在 ForEach
期间使用 enumerated()
获取索引 和 项。然后,XButton
仅在 index == 0
然后,我使用 ZStack
将 XButton
放在最上面。我假设你原来的问题中的“在上面”意味着覆盖,但如果你只是意味着在 y 轴上更高,你可以将它改回 VStack
struct ContentView : View {
var body: some View {
ScrollView{
ForEach(Array(CardsData.enumerated()), id: \.1.id) { (index,item) in
ZStack {
CardsView(Cards: item)
if index == 0 {
XButton()
}
}
}
}
}
}
注意:这是假设 CardsData
项符合 Identifiable
,如果您的原始 ForEach
有效,我假设它们符合 Identifiable
。请注意,我从 .1.id
获取 ID,它是 CardsData
中项目的 id
属性,现在是一个元组,其中第一部分 (0) 是索引和第二个 (1) 是项目。