Home > other >  Swift UI Gradient make Spacer useless
Swift UI Gradient make Spacer useless

Time:01-03

I was creating a centered card with a background gradient, I would like to have the height acording with the content, like this:

expected result of card height

The problem is when I use a gradient component inside the card, because the card height is taking the free space and it is ignoring the Spacer outside of the VStack

import SwiftUI

struct TunedModable<Content: View>: View {
    @ViewBuilder var content:() ->  Content
    
    var body: some View {
        
            VStack {
                Spacer()
                
                ZStack {
                    LinearGradient(
                        gradient: Gradient(
                            colors: [.gray, .green]
                        ),
                        startPoint: .bottom,
                        endPoint: .top
                    )
                    VStack {
                        content()
                    }
                }
                .frame(maxWidth: .infinity)
                .background()
                .clipShape(
                    RoundedRectangle(cornerRadius: 25.0, style: .continuous)
                )
                
                
                Spacer()
                Text("Testing").foregroundColor(.white)
            }.frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).padding().background(.indigo)
        }
    
}

struct TunedModable_Previews: PreviewProvider {
    static var previews: some View {
        TunedModable {
            Text("Hello")
        }
    }
}

enter image description here Result with gradient is a Card with full height but I need to have the height like "automatic" like the first picture

CodePudding user response:

Instead of ZStack use background, like

 content()
   .background(
      LinearGradient(
        gradient: Gradient(
            colors: [.gray, .green]
        ),
        startPoint: .bottom,
        endPoint: .top
    ))

ZStack extended to biggest view (which is Gradient because it does not have own size and consumes all available space), whereas background or overlay fit to size of target view (content in your case).

See also https://stackoverflow.com/a/63446622/12299030

  • Related