我有一个 SwiftUI View,它有一个运行的自定义动画onAppear。我也试图让视图动画化onDisappear,但它立即消失了。
下面的示例重现了该问题 -MyText视图应从左侧滑入并从右侧滑出。修饰符id用于确保每次值更改时都会渲染一个新视图,并且我已经确认确实每次都会调用 和 ,但动画onAppear永远不会明显运行。我怎样才能实现这个目标?onDisappearonDisappear
struct Survey: View {
@State private var id = 0
var body: some View {
VStack {
MyText(text: "\(id)").id(id)
Button("Increment") {
self.id += 1
}
}
}
struct MyText: View {
@State private var offset: CGFloat = -100
let text: String
var body: some View {
return Text(text)
.offset(x: offset)
.onAppear() {
withAnimation(.easeInOut(duration: 2)) {
self.offset = 0
}
}
.onDisappear() {
withAnimation(.easeInOut(duration: 2)) {
self.offset = 100
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
也许你想要过渡,比如
更新:使用 Xcode 13.4 / iOS 15.5 重新测试
struct Survey: View {
@State private var id = 0
var body: some View {
VStack {
MyText(text: "\(id)")
Button("Increment") {
self.id += 1
}
}
}
struct MyText: View {
var text: String
var body: some View {
Text("\(text)").id(text)
.frame(maxWidth: .infinity)
.transition(.slide)
.animation(.easeInOut(duration: 2), value: text)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5182 次 |
| 最近记录: |