VStack fill the width of the screen in SwiftUI

Generally when we use VStack with few views we observed that there is some empty place left over we will see two possible ways-

1. By using frame
struct ContentView: View {
    var body: some View {
        VStack {
            Text("Nice Post")
            Text("Comment below")
        }
        .frame(
            maxWidth: .infinity,
            maxHeight: .infinity,
            alignment: .topLeading
        )
        .background(Color.red)
    }
}
2. Use GeometryReader with frames

GeometryReader returns a flexible preferred size to its parent layout hence by using arguments geoArgs we can set frame –

struct ContentView : View {
    var body: some View {
        GeometryReader { geoArgs in
            VStack {
                Text("Nice Post")
                Text("Comment below")
            }
            .frame(
                width: geoArgs.size.width,
                height: geoArgs.size.height,
                alignment: .topLeading
            )
        }
        .background(Color.red)
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *