且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 SwiftUI 的 ScrollView 中创建多行文本?

更新时间:2023-12-04 13:13:52

Xcode 11 GM 中:

对于嵌套在滚动视图中的堆栈中的任何 Text 视图,使用 .fixedSize(horizo​​ntal: false, vertical: true) 解决方法:

ScrollView {
    VStack {
        Text(someString)
            .fixedSize(horizontal: false, vertical: true)
    }
}

如果有多个多行文本,这也适用:

ScrollView {
    VStack {
        Text(someString)
            .fixedSize(horizontal: false, vertical: true)
        Text(anotherLongString)
            .fixedSize(horizontal: false, vertical: true)
    }
}

如果堆栈的内容是动态的,则相同的解决方案有效:

ScrollView {
    VStack {
        // Place a single empty / "" at the top of your stack.
        // It will consume no vertical space.
        Text("")
            .fixedSize(horizontal: false, vertical: true)

        ForEach(someArray) { someString in
            Text(someString)
              .fixedSize(horizontal: false, vertical: true)
        }
    }
}