'How to center a scrollable text in SwiftUI
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

