带有适合内容的列的 SwiftUI 网格? [英] SwiftUI grid with column that fits content?

查看:39
本文介绍了带有适合内容的列的 SwiftUI 网格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SwiftUI 可以实现这种布局吗?

Is this layout possible with SwiftUI?

我希望第一列包含标签的大小,因此在这种情况下,它的大小刚好足以显示Bigger Label:".然后把剩下的空间给第二列.

I want the first column to wrap the size of the labels, so in this case it will be just big enough to show "Bigger Label:". Then give the rest of the space to the second column.

这种布局非常简单,带有自动布局.

This layout is pretty simple with auto layout.

SwiftUI 2020 有 LazyVGrid,但我看到的设置列大小的唯一方法是使用硬编码数字.他们不明白多语言和用户可调整的字体大小会导致什么问题吗?

SwiftUI 2020 has LazyVGrid but the only ways I see to set the column sizes use hardcoded numbers. Do they not understand what a problem that causes with multiple languages and user-adjustable font sizes?

推荐答案

如果比较代码行数以在两个世界中以编程方式实现这一点并不复杂...

It is not so complex if to compare number of code lines to make this programmatically in both worlds...

无论如何,肯定有可能.这是一个基于使用视图首选项功能的帮助修改器的解决方案.不难.没有网格.

Anyway, sure it is possible. Here is a solution based on some help modifier using view preferences feature. No hard. No grid.

演示准备&使用 Xcode 12/iOS 14 进行测试.

Demo prepared & tested with Xcode 12 / iOS 14.

struct DemoView: View {
    @State private var width = CGFloat.zero

    var body: some View {
        VStack {
            HStack {
                Text("Label1")
                    .alignedView(width: $width)
                TextField("", text: .constant("")).border(Color.black)
            }
            HStack {
                Text("Bigger Label")
                    .alignedView(width: $width)
                TextField("", text: .constant("")).border(Color.black)
            }
        }
    }
}

和帮手

extension View {
    func alignedView(width: Binding<CGFloat>) -> some View {
        self.modifier(AlignedWidthView(width: width))
    }
}

struct AlignedWidthView: ViewModifier {
    @Binding var width: CGFloat

    func body(content: Content) -> some View {
        content
            .background(GeometryReader {
                Color.clear
                    .preference(key: ViewWidthKey.self, value: $0.frame(in: .local).size.width)
            })
            .onPreferenceChange(ViewWidthKey.self) {
                if $0 > self.width {
                    self.width = $0
                }
            }
            .frame(minWidth: width, alignment: .trailing)
    }
}

这篇关于带有适合内容的列的 SwiftUI 网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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