gpt4 book ai didi

animation - 在 SwiftUI 中按高度动画 View

转载 作者:行者123 更新时间:2023-12-04 10:46:35 25 4
gpt4 key购买 nike

我正在尝试制作一个 View ,该 View 将从屏幕底部为另一个内容 View 设置动画。但是,以下代码有效,因为内容 View 的高度未知,200 偏移量可能不正确。如何获取内容的高度以正确偏移 View ?

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)

}
}
}

关于animation - 在 SwiftUI 中按高度动画 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59678605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com