在Mac上包含带自动换行的文本的SwiftUI列表

时间:2019-11-01 10:34:24

标签: macos swiftui

在Mac上,我遇到了一个列表,该列表包含文本行并带有可换行的文本。

代码如下:

struct ContentView: View {
    var messages = [
        "This is a long piece of text that's going to need to be wrapped to fit into the view.",
        "This is another long piece of text that's going to need to be wrapped to fit into the view."
    ]

    var body: some View {
        List(messages, id: \.self) { message in
            Text(message)
                .lineLimit(nil)
                .border(Color.blue)
                .fixedSize(horizontal: false, vertical: true)

                // Also tried .fixedSize(horizontal: true, vertical: false)
                // which seems more correct, but doesn't wrap the text at all
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

当我在iOS上运行它时,结果就是我期望的:

Repro-Phone

但是,在Mac上,SwiftUI正在创建的基础表似乎并没有在调整行高以适合所包装的内容:

Repro-Mac

我已将其报告为错误(FB7421021),但在此处询问是否有人为此感到困扰。

谢谢

1 个答案:

答案 0 :(得分:0)

这里采用的方法适用于我的类似用例。希望对其他人有用。

struct TestWrappedText: View {
    var messages = [
        "This is a long piece of text that's going to need to be wrapped to fit into the view.",
        "This is another long piece of text that's going to need to be wrapped to fit into the view."
    ]

    @State var alignedHeight: [CGFloat] = [0, 0]

    var body: some View {
        List(0 ..< messages.count) { i in
            Text(self.messages[i])
                .border(Color.blue)
                .fixedSize(horizontal: false, vertical: true)
                .modifier(ViewHeightKey())
                .onPreferenceChange(ViewHeightKey.self) {
                    if self.alignedHeight[i] != $0 {
                        self.alignedHeight[i] = $0
                    }
                }
                .frame(height: self.alignedHeight[i])
        }
    }
}

struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout Value, nextValue: () -> Value) {
        value = nextValue()
    }
}

extension ViewHeightKey: ViewModifier {
    func body(content: Content) -> some View {
        return content.background(GeometryReader { proxy in
            Color.clear.preference(key: Self.self, value: proxy.size.height)
        })
    }
}