高度相等的SwiftUI HStack

时间:2020-02-21 20:05:05

标签: swift swiftui

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

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 个答案:

答案 0 :(得分:5)

这里可能使用.alignmentGuide

demo

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发生冲突。

答案 1 :(得分: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)
    }

结果:demo