How can I hide extra sized background View in a View?

Viewed 24

I have a simple Rectangle which I put a VStack of Numbers in background of that, you can see it in code and pic! the problem is the VStack is taller than Rectangle there for it goes outside of Rectangle, I want the extra part be hidden, How could I solve it?

    struct ContentView: View {
    
    let arrayOfHours: [Int] = Array(0...23)
    
    var body: some View {

            Rectangle()
                .fill(Color.black.opacity(0.25))
                .frame(height: 200, alignment: .center)
                .padding()
                .background(
                
                    VStack(alignment: .center, spacing: 4) {
                        
                        ForEach (arrayOfHours.indices, id: \.self) { index in
                            
                            Text(arrayOfHours[index].description)
                                .font(Font.body.bold())
                            
                        }
                    }
                    .background(Color.yellow)

                )

    }
}

enter image description here

1 Answers

If I understood your description correctly you need clipped, like

demo

    struct ContentView: View {
    
    let arrayOfHours: [Int] = Array(0...23)
    
    var body: some View {

            Rectangle()
                .fill(Color.black.opacity(0.25))
                .frame(height: 200, alignment: .center)
                .background(
                
                    VStack(alignment: .center, spacing: 4) {
                        
                        ForEach (arrayOfHours.indices, id: \.self) { index in
                            
                            Text(arrayOfHours[index].description)
                                .font(Font.body.bold())
                            
                        }
                    }
                    .background(Color.yellow)

                )
                .clipped()        // << here !!
                .padding()        // should be moved here !!
    }
}
Related