SwiftUI – Vertical Centering Content inside Scrollview

You can vertically center content in a scroll view by using GeometryReader to get the parent view’s dimensions and setting the scroll view’s content’s minHeight to the parent’s height.

When the content is too big to fit vertically it’ll just scroll like normal.

For example:

var body: some View {
    GeometryReader { geometry in                    // Get the geometry
        ScrollView(.vertical) {
            VStack {
                Text("Form goes here")
                .frame(maxWidth: 400)               // Set your max width
            }
            .padding()
            .background(Color.yellow)
            .frame(width: geometry.size.width)      // Make the scroll view full-width
            .frame(minHeight: geometry.size.height) // Set the content’s min height to the parent
        }
    }
}

Preview

Leave a Comment