ios - 如何在 SwiftUI 中的 ForEach 中嵌入的 HStack 中设置相对宽度?

标签 ios swift swiftui ios14

我想创建属性列表(不使用 ListView )。每个属性都是一个 HStack,其中包含两个文本:名称和值。我希望名称文本始终占整个 HStack 宽度的 30%,而值文本则使用其余的水平空间。每个属性的高度取决于内容。

我尝试通过以下观点来实现它:

struct FatherList: View {
    let attributes: Attributes
    
    init(_ attributes: Attributes) {
        self.attributes = attributes
    }
    
    var body: some View {
        VStack(spacing: CGFloat.spacing.medium) {
            ForEach(
                attributes,
                id: \.name,
                content: ChildView.init
            )
        }
    }
}

其中包含以下 ChildView:

struct ChildView: View {
    let listItem: Product.Attribute
    
    init(_ attribute: Product.Attribute) {
        self.attribute = attribute
    }
    
    var body: some View {
        GeometryReader { geometry in
            HStack(alignment: .top, spacing: 0) {
                Text(attribute.name)
                    .bold()
                    .frame(width: 0.3 * geometry.size.width)
                    .background(Color.yellow)
                Text(attribute.value)
            }
            .fixedSize(horizontal: false, vertical: true)
            .background(Color.red)
        }
    }
}

我得到的结果是这样的:

enter image description here

subview 重叠,这不是我想要的,我希望 subview 展开并相互跟随。我正在使用 GeometryReader 来完成我上面描述的相对宽度。我做错了什么?

最佳答案

这是可能解决方案的演示。使用 Xcode 11.4/iOS 13.4 进行测试

demo

注意:ViewHeightKey取自this another my solution

struct ChildView: View {
    let attribute: Attribute

    @State private var fitHeight = CGFloat.zero

    var body: some View {
        GeometryReader { geometry in
            HStack(alignment: .top, spacing: 0) {
                Text(self.attribute.name)
                    .bold()
                    .frame(width: 0.3 * geometry.size.width, alignment: .leading)
                    .background(Color.yellow)
                Text(self.attribute.value)
                    .fixedSize(horizontal: false, vertical: true)
                    .frame(width: 0.7 * geometry.size.width, alignment: .leading)
            }
            .background(Color.red)
            .background(GeometryReader {
                Color.clear.preference(key: ViewHeightKey.self,
                    value: $0.frame(in: .local).size.height) })
        }
        .onPreferenceChange(ViewHeightKey.self) { self.fitHeight = $0 }
        .frame(height: fitHeight)
    }
}

关于ios - 如何在 SwiftUI 中的 ForEach 中嵌入的 HStack 中设置相对宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62992686/

相关文章:

ios - 就地 UITableView 编辑 : Adding a row crash

ios - 自从获取照片以来,用户界面有点卡住

ios - MKPolyline 边界MapRect 插入

ios - 在 UITextFieldBeginEditing 上调用 prepare for segue

swift - 在 Swift 中,如何使用匿名闭包参数显式指定 map 的返回值?

swift - 如何在透明度降低的 SwiftUI 中获取菜单项的重音背景?

mvvm - SwiftUI 中的 EnvironmentObject 与 Singleton?

ios - SpriteKit 本地化连接

android - 无法从 Objective C 解密 AES 加密字符串

ios - 为什么 .imageScale(.large) 不像 iOS 库存应用程序中那样大?