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:
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:
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With