如何使父视图的宽度等于最小子视图的宽度?
我可以使用this question的答案来了解子视图的宽度,如下所示:
struct WidthPreferenceKey: PreferenceKey {
static var defaultvalue = CGFloat(0)
static func reduce(value: inout CGFloat,nextvalue: () -> CGFloat) {
value = nextvalue()
}
typealias Value = CGFloat
}
struct TextGeometry: View {
var body: some View {
GeometryReader { geometry in
return Rectangle().fill(Color.clear).preference(key: WidthPreferenceKey.self,value: geometry.size.width)
}
}
}
struct Content: View {
@State var width1: CGFloat = 0
@State var width2: CGFloat = 0
var body: some View {
VStack {
Text("Short")
.background(TextGeometry())
.onPreferenceChange(WidthPreferenceKey.self,perform: { self.width1 = $0 })
Text("Loooooooooooong")
.background(TextGeometry())
.onPreferenceChange(WidthPreferenceKey.self,perform: { self.width2 = $0 })
}
.frame(width: min(self.width1,self.width2)) // This is always 0
}
}
但是VStack
的宽度始终为0。就像
.frame(width: min(self.width1,self.width2))
行被调用
在设置宽度之前。
有什么想法吗?