简体   繁体   中英

How to display image except for one item on Foreach loop in swiftUI?

I've created an card and I want an image to display on top of each card except for the first one. please help me to solve this.

This is the struct that holds the image.

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())
        }
}

This the scrollview that contains the cards inside the foreach loop

ScrollView{
                    ForEach(CardsData) { item in
                    VStack {
                        
                        CardsView(Cards: item)

                          }
                }
          }

You can use enumerated() to get the index and item during a ForEach . Then, XButton is only rendered conditionally if index == 0

Then, I use ZStack to put the XButton on top. I'm assuming "on top" in your original question means overlaid, but if you just meant higher on the y axis, you could change this back to a 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()
                    }
                }
            }
        }
    }
}

Note: this is assuming that CardsData items conform to Identifiable , which I assume they did if your original ForEach worked. Note that I'm getting the id from .1.id which is the id property of the item in the CardsData which is now a tuple where the first part (0) is the index and the second (1) is the item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM