【问题标题】:How to display image except for one item on Foreach loop in swiftUI?如何在swiftUI中的Foreach循环上显示除一项之外的图像?
【发布时间】:2021-02-15 06:40:43
【问题描述】:

我创建了一张卡片,我希望在每张卡片的顶部显示一张图片,但第一张除外。请帮我解决这个问题。

这是保存图像的结构。

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)

                          }
                }
          }

【问题讨论】:

  • 所以您希望 Button 出现在除第一个之外的所有 CardsViews 之上,对吗?
  • 是的,没错!!

标签: ios arrays swift swiftui swiftui-list


【解决方案1】:

您可以使用enumerated()ForEach 期间获取索引 项。然后,XButton 只有在index == 0 时才会有条件地呈现

然后,我使用ZStackXButton 放在顶部。我假设您原始问题中的“顶部”意味着重叠,但如果您只是指在 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 有效,我假设他们这样做了。请注意,我从 .1.id 获取 id,这是 CardsData 中项目的 id 属性,现在是一个元组,其中第一部分 (0) 是索引,第二部分 (1) 是项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多