2 swiftui
我中间有一个大文本,可以是多行。我将它包裹在滚动视图下,因为文本可能很长。当文本不适合整个屏幕时,我想将文本居中放置。我有以下代码:
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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,文本始终位于顶部。设置固定高度是可行的,但我不想在这里硬编码任何值。我也尝试过将ScrollView放在另一个VStack下,有间距,但没有效果。
您只需要minHeightasText屏幕(动态高度),因此当它小于屏幕时,如果它很大,它将居中(默认对齐) - 然后根据需要增长。
这是固定主体(使用 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") {}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2465 次 |
| 最近记录: |