SwiftUI等高度的HStack

5

我希望Text("111")与包含2222...和333...的VStack高度相等。

struct Test7: View {
  var body: some View
  { HStack (alignment: .top) {
    Text( "111")                     // Shall have equal Height
    .background(Color.red)
    VStack(alignment: .leading){.    // of this VStack
      Text("2222222")
      .background(Color.gray)
      Text("333333333")
      .background(Color.blue)
    }
  }
  .background(Color.yellow)}
}

我尝试使用GeometryReader,但无法使其正常工作。

2个回答

13

这里是使用.alignmentGuide的可能方法:

演示

struct Test7: View {
    @State
    private var height: CGFloat = .zero // < calculable height

    var body: some View {
        HStack (alignment: .top) {
            Text( "111")                     
                .frame(minHeight: height)    // in Preview default is visible
                .background(Color.red)

            VStack(alignment: .leading) {    
                Text("2222222")
                    .background(Color.gray)
                Text("333333333")
                    .background(Color.blue)
            }
            .alignmentGuide(.top, computeValue: { d in
                DispatchQueue.main.async { // << dynamically detected - needs to be async !!
                    self.height = max(d.height, self.height)
                }
                return d[.top]
            })
        }
        .background(Color.yellow)
    }
}
注意:真正的结果只有在LivePreview中可见,因为高度是动态计算的,并在下一次渲染周期中分配,以避免@State上的冲突。

注意:真正的结果只有在LivePreview中可见,因为高度是动态计算的,并且在下一个渲染周期中被分配,以避免在@State上出现冲突。


0

使用 .frame(maxHeight: .infinity)

var body: some View {
        HStack(alignment: .top) {
            Text("111")
                .frame(maxHeight: .infinity)
                .background(Color.red)
            
            VStack(alignment: .leading) {
                Text("2222222")
                    .frame(maxHeight: .infinity)
                    .background(Color.gray)
                        
                Text("333333333")
                    .frame(maxHeight: .infinity)
                    .background(Color.blue)
            }
        }.background(Color.yellow)
            .frame(height: 50)
    }

结果:演示


只适用于父元素固定高度。这不是 OP 所询问的内容。 - LilaQ

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