SwiftUI 中形状的动态高度 [英] Dynamic height for shapes in SwiftUI

查看:37
本文介绍了SwiftUI 中形状的动态高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想做的事情的一个最小的、可重复的例子.

Here's a minimal, reproducible example of what I want to do.

我有一个段落数组.

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."
]

这就是我想显示的方式:

This is how I want to display this:

这是我的代码.

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()
            }

        }
    }
}

这是我得到的输出:

我什至尝试将 Spacer() 添加到 VStack 的底部(在 ForEach 之后),但输出仍然相同.

I even tried adding a Spacer() to the bottom of the VStack (after the ForEach) but the output is still same.

我想知道的是如何将这些蓝色竖条的高度更改为它们各自段落的高度,如第一个屏幕截图所示.

What I want to know is how to change the height of those blue vertical bars to the height of their respective paragraphs like in the first screenshot.

推荐答案

这是可能的方法.使用 Xcode 11.4/iOS 13.4 测试

Here is possible approach. Tested with Xcode 11.4 / iOS 13.4

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()
        }
    }
}

这篇关于SwiftUI 中形状的动态高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆