【发布时间】:2019-11-06 19:31:31
【问题描述】:
如何使父视图的宽度成为最小子视图的宽度?
我可以使用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)) 行
在设置宽度之前。
有什么想法吗?
【问题讨论】:
标签: swiftui