我希望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
,但没有使其正常工作
这里是使用.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发生冲突。