SwiftUI中形状的动态高度

3

这是我想要做的最小可重现示例。

我有一个段落数组。

var notes = [
    "One line paragraph",
    "This is a small paragraph. This is a small paragraph. This is a small paragraph. This is a small paragraph.",
    "This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph."
]

这是我想要展示的方式: 输入图片描述 这是我的代码。
struct ContentView: View {
    var notes = [
        "One line paragraph",
        "This is a small paragraph. This is a small paragraph. This is a small paragraph. This is a small paragraph.",
        "This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph."
    ]

    var body: some View {
        VStack(alignment: .leading) {
            ForEach(self.notes, id: \.self) {note in
                HStack {
                    Capsule()
                        .fill(Color.blue)
                        .frame(width: 4.5)

                    Text(note)
                    .lineLimit(nil)
                }
                .padding()
            }

        }
    }
}

这是我得到的输出: enter image description here 我甚至尝试在ForEach之后添加一个Spacer()VStack底部,但输出仍然相同。
我想知道的是如何将这些蓝色竖条的高度更改为它们各自段落的高度,就像第一个屏幕截图中的那样。
1个回答

4
这里是一种可能的方法。已经测试使用Xcode 11.4 / iOS 13.4。 demo
var body: some View {
    VStack(alignment: .leading) {
        ForEach(self.notes, id: \.self) {note in
            HStack {
                Text(note)
                    .padding(.leading)
            }
            .overlay(Capsule()       // also can be .background
                        .fill(Color.blue)
                        .frame(width: 4.5), alignment: .leading)
            .padding()
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接