Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift UI Gradient make Spacer useless

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading