Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center and align SwiftUI elements in a ScrollView

Tags:

swift

swiftui

I have the following SwiftUI view:

import SwiftUI

struct MySwiftUIView: View {
    var body: some View {
        VStack {
            HStack {
                Text("top leading text")
                Spacer()
            }
            Spacer()
            HStack {
                Spacer()
                Text("centered text")
                Spacer()
            }
            Spacer()
            HStack {
                Spacer()
                Text("bottom trailing text")
            }
        }
    }
}

It looks like this when run:

enter image description here

If I embed the view in a ScrollView like this:

import SwiftUI

struct MySwiftUIView: View {
    var body: some View {
        ScrollView {
            VStack {
                HStack {
                    Text("top leading text")
                    Spacer()
                }
                Spacer()
                HStack {
                    Spacer()
                    Text("centered text")
                    Spacer()
                }
                Spacer()
                HStack {
                    Spacer()
                    Text("bottom trailing text")
                }
            }
        }
    }
}

Then it looks like this when run:

enter image description here

How do I make the centered text centered, and the bottom trailing text rest on the bottom, when they are embedded in a ScrollView?

In a way, I want to use SwiftUI to replicate this scrolling behaviour seen in Xcode's inspectors, where the text "Not Applicable" is centered and scrollable:

enter image description here

like image 253
Wowbagger and his liquid lunch Avatar asked Apr 04 '20 03:04

Wowbagger and his liquid lunch


1 Answers

Wrap the ScrollView inside GeometryReader. Then apply a minimum height to the scroll view equal to the geometry.size.height. Now the spacers you applied should fill the VStack the way you intended them to. Try the code below:

GeometryReader { geometry in
    ScrollView(.vertical) {
        VStack {
            HStack {
                Text("top leading text")
                Spacer()
            }
            Spacer()
            HStack {
                Text("centered text")
            }
            Spacer()
            HStack(alignment: .bottom) {
                Spacer()
                Text("bottom trailing text")
            }
         }
         .padding()
         .frame(width: geometry.size.width)
         .frame(minHeight: geometry.size.height)

    }
}

Also check this post for more discussion on this issue: SwiftUI - Vertical Centering Content inside Scrollview

like image 148
Sevan Golnazarian Avatar answered Oct 20 '22 03:10

Sevan Golnazarian