Reputation:
I have a big text in the middle that can be multiple line. I wrapped it under a scroll view because the text could be very long. When the text does not fit the whole screen, I want to center place the text. I have the following code:
var body: some View {
VStack {
Text("2 / 5")
Spacer()
ScrollView([.vertical]) {
Text("This is a joke. Multiple line is supported. This is a joke. Multiple line is supported. This is a joke. Multiple line is supported. ")
.fontWeight(.bold)
.font(.system(.title, design: .rounded))
.multilineTextAlignment(.center)
}
Spacer()
HStack {
Button("Prev") {
// go to prev page
}
Spacer()
Button("Next") {
// go to next page
}
}
}
}
However, the text is always on the top. Setting a fixed height works, but I don't want to hardcode any value here. I have also tried putting ScrollView under another VStack, with a spacing, but it has no effects.
Upvotes: 2
Views: 3156
Reputation: 257493
You just need minHeight
for Text
as screen (dynamic height), so when it is smaller than screen then it will be centered (by default alignment) if it is large - then just grows as needed.
Here is fixed body (tested with Xcode 13.2 / iOS 15.2):
var body: some View {
GeometryReader { proxy in
VStack {
Text("2 / 5")
Spacer()
ScrollView {
Text("This is a joke. Multiple line is supported. This is a joke. Multiple line is supported. This is a joke. Multiple line is supported. ")
.fontWeight(.bold)
.font(.system(.title, design: .rounded))
.multilineTextAlignment(.center)
.frame(minHeight: proxy.size.height) // << here !!
}
Spacer()
HStack {
Button("Prev") {}
Spacer()
Button("Next") {}
}
}
}
}
Upvotes: 7