SwiftUI动画滑入和滑出 [英] SwiftUI Animation Slide In and Out
问题描述
我有一个视图,该视图将显示在另一个视图上.视图动画会完美地从右侧滑入,但是当我单击关闭"按钮时,视图消失,而消失前并没有所需的向右滑动的动画.
I have a View that will display over another View. The view animation slides in from the right perfectly, but when I click on the Close button, the view disappears without the desired animation of sliding back to the right before disappearing.
我尝试使用.opacity(self.isShowing?1:0),但是随后View淡入和淡出,我需要它滑入和滑出.其他变化并没有产生预期的结果.
I have tried using .opacity(self.isShowing ? 1 : 0), but then the View fades in and out, I need it to slide in and out. Other variations have not produced the desired results.
我做错了什么?任何指导,甚至有重复的解决方案(我找不到),都将不胜感激.
What am I doing wrong? Any guidance, even a duplicate solution (that I could not find) would be greatly appreciated.
struct NotificationView<parentView>: View where parentView: View {
@Binding var isShowing: Bool
let parentView: () -> parentView
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .center) {
self.parentView()
if(self.isShowing == true){
VStack {
Text("This is a test view\n")
Button(action: {
self.isShowing.toggle()
}) {
Text("Close")
}
}
.frame(width: geometry.size.width, height: geometry.size.height)
.background(Color(UIColor.systemBackground))
// .opacity(self.isShowing ? 1 : 0)
.transition(.move(edge: self.isShowing ? .trailing : .leading))
.animation(Animation.easeInOut(duration: 1.0))
}
}
}
}
}
推荐答案
将条件部分移动到容器中并向容器中添加动画,以便它将内容动画化,例如
Move conditional part into container and add animation to container, so it will animate content, like
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .center) {
self.parentView()
VStack { // << here !!
if(self.isShowing == true){
VStack {
Text("This is a test view\n")
Button(action: {
self.isShowing.toggle()
}) {
Text("Close")
}
}
.frame(width: geometry.size.width, height: geometry.size.height)
.background(Color(UIColor.systemBackground))
.transition(.move(edge: self.isShowing ? .trailing : .leading))
}
}.animation(Animation.easeInOut(duration: 1.0)) // << here !!
}
}
}
这篇关于SwiftUI动画滑入和滑出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!