gpt4 book ai didi

swiftui - 如何在 SwiftUI 中将可滚动文本居中

转载 作者:行者123 更新时间:2023-12-02 01:45:27 24 4
gpt4 key购买 nike

我在中间有一个大文本,可以是多行。我将它包裹在 ScrollView 下,因为文本可能会很长。当文字不适合整个屏幕时,我想居中放置文字。我有以下代码:


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
}
}
}
}

但是,文本总是在顶部。设置固定高度可行,但我不想在此处硬编码任何值。我也试过将 ScrollView 放在另一个 VStack 下,有一个间距,但没有效果。

enter image description here

最佳答案

对于Text,您只需要minHeight作为屏幕(动态高度),所以当它小于屏幕时,它将居中(默认对齐)如果它是大 - 然后根据需要增长。

这是固定主体(使用 Xcode 13.2/iOS 15.2 测试):

demo

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") {}
}
}
}
}

关于swiftui - 如何在 SwiftUI 中将可滚动文本居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70981389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com