有没有一种方法可以使用SwiftUI将文本限制为2/3行?

时间:2019-06-06 10:33:21

标签: swiftui xcode11 ios13

我正在尝试使用

var body: some View {
    Text("This is large text. Is there a way that I can unwrap the large text as discussed").lineLimit(2)
}

仅供参考: 我知道

var body: some View {
    Text("This is large text. Is there a way that I can unwrap the large text as discussed").lineLimit(nil)
}

它将换行为n行。

2 个答案:

答案 0 :(得分:1)

.lineLimit(3)元素上调用Text。 (从技术上讲,可以在 any View上调用它,在这种情况下,它将限制该视图中 all Text元素的行。)

来自SwiftUI.View

    /// Sets the maximum number of lines that text can occupy in this view.
    ///
    /// The line limit applies to all `Text` instances within this view. For
    /// example, an `HStack` with multiple pieces of text longer than three
    /// lines caps each piece of text to three lines rather than capping the
    /// total number of lines across the `HStack`.
    ///
    /// - Parameter number: The line limit. If `nil`, no line limit applies.
    /// - Returns: A view that limits the number of lines that `Text` instances
    ///   display.
    public func lineLimit(_ number: Int?) -> Self.Modified<_EnvironmentKeyWritingModifier<Int?>>

答案 1 :(得分:0)

因为 _counter = _counter! + 1; 暂时没有按预期工作,如果您有多个文本(如标题和副标题),则可以简单地将 Text 元素包装在 VStack 中,给 VStack multilineTextAlignment 修饰符并使用参数 { {1}} 或者您可以将 .linelimit 修饰符直接添加到 Text 元素:

.center