具有相同高度的 SwiftUI HStack [英] SwiftUI HStack with equal Height
本文介绍了具有相同高度的 SwiftUI HStack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望 Text("111")
具有与 VStack
相同的高度,其中包含 2222... 和 333....
I want the Text("111")
to have the equal height of the VStack
containing 2222... and 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
但没有让它工作
I tried with a GeometryReader
but didn't get it to work
推荐答案
这是使用 .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 冲突.
Note: real result is visible only in LivePreview, because height is calculated dynamically and assign in next rendering cycle to avoid conflicts on @State.
这篇关于具有相同高度的 SwiftUI HStack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文