1

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)

                          }
                }
          }
2
  • So you want Button to appear on top of all CardsViews except the first, correct? Commented Feb 15, 2021 at 6:43
  • yeah, exactly!! Commented Feb 15, 2021 at 6:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.