我正在尝试制作一个视图,该视图将从屏幕底部对另一个内容视图进行动画处理。但是,下面的代码有效,因为内容视图的高度未知,200 偏移量可能不正确。如何获取内容的高度以正确偏移视图?
struct Test<Content>: View where Content : View {
@State var showing: Bool = false
var content: Content
var body: some View {
VStack {
Button(action: {
withAnimation {
self.showing.toggle()
}
}) {
Text("Toggle")
}
Spacer()
HStack {
Spacer()
content
Spacer()
}
.background(Color.red)
.padding(10)
.offset(y: showing ? 200 : 0)
}
}
}
这是在对齐过程中直接从中读取content
高度的可能方法...
struct Test<Content>: View where Content : View {
var content: Content
@State private var showing: Bool = false
@State private var contentHeight: CGFloat = .zero
var body: some View {
VStack {
Button(action: {
withAnimation {
self.showing.toggle()
}
}) {
Text("Toggle")
}
Spacer()
HStack {
Spacer()
content
.alignmentGuide(VerticalAlignment.center) { d in
DispatchQueue.main.async {
self.contentHeight = d.height
}
return d[VerticalAlignment.center]
}
Spacer()
}
.background(Color.red)
.padding(10)
.offset(y: showing ? contentHeight : 0)
}
}
}