How do you create a multi-line text inside a ScrollView in SwiftUI?

Geo*_*man 20 swift swiftui

Since List doesn't look like its configurable to remove the row dividers at the moment, I'm using a ScrollView with a VStack inside it to create a vertical layout of text elements. Example below:

ScrollView {
    VStack {
        // ...
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mattis ullamcorper tortor, nec finibus sapien imperdiet non. Duis tristique eros eget ex consectetur laoreet.")
            .lineLimit(0)
    }.frame(width: UIScreen.main.bounds.width)
}

Run Code Online (Sandbox Code Playgroud)

The resulting Text rendered is truncated single-line. Outside of a ScrollView it renders as multi-line. How would I achieve this inside a ScrollView other than explicitly setting a height for the Text frame ?

And*_*era 35

Xcode 11 GM中

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

ScrollView {
    VStack {
        Text(someString)
            .fixedSize(horizontal: false, vertical: true)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

ScrollView {
    VStack {
        Text(someString)
            .fixedSize(horizontal: false, vertical: true)
        Text(anotherLongString)
            .fixedSize(horizontal: false, vertical: true)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果堆栈的内容是动态的,则可以使用相同的解决方案:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我在滚动视图内有许多动态生成的视图,其中一些视图包含各自视图树下几层的文本。不幸的是,这些解决方案都不起作用——我仍然看到一堆文本字段被压缩成一行。有人遇到过类似的问题吗?我正在使用 Xcode 的 GM 版本 (2认同)

小智 6

您可以强制视图填充其理想大小,例如在垂直 ScrollView 中:

ScrollView {
    Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mattis ullamcorper tortor, nec finibus sapien imperdiet non. Duis tristique eros eget ex consectetur laoreet.")
        .fixedSize(horizontal: false, vertical: true)
}
Run Code Online (Sandbox Code Playgroud)

对我来说感觉比修改框架好一点。