[英]How to make a reusable modifier for view lifecycle events (onAppear, onDisappear)?
I have a common fadeIn
and fadeOut
animation that I use for when views appear and disappear:我有一个常见的
fadeIn
和fadeOut
animation,用于视图出现和消失时:
struct ActiveView: View {
@State var showCode: Bool = false
@State var opacity = 0.0
var body: some View {
if self.showCode {
Color.black.opacity(0.7)
.onAppear{
let animation = Animation.easeIn(duration: 0.5)
return withAnimation(animation) {
self.opacity = 1
}
}
.onDisappear{
let animation = Animation.easeOut(duration: 0.5)
return withAnimation(animation) {
self.opacity = 0
}
}
}
}
}
However, I want to use these same animations on other views, so I want it to be simple and reusable, like this:但是,我想在其他视图上使用这些相同的动画,所以我希望它简单且可重用,如下所示:
if self.showCode {
Color.black.opacity(0.7)
.fadeAnimation()
}
How can I achieve this?我怎样才能做到这一点?
EDIT:编辑:
Trying to implement a View extension:尝试实现视图扩展:
extension View {
func fadeAnimation(opacity: Binding<Double>) -> some View {
self.onAppear{
let animation = Animation.easeIn(duration: 0.5)
return withAnimation(animation) {
opacity = 1
}
}
.onDisappear{
let animation = Animation.easeOut(duration: 0.5)
return withAnimation(animation) {
opacity = 0
}
}
}
}
What you try to do is already present and named opacity transition , which is written in one modifier.您尝试做的已经存在并命名为opacity transition ,它是用一个修饰符编写的。
Here is a demo:这是一个演示:
struct ActiveView: View {
@State var showCode: Bool = false
var body: some View {
ZStack {
if self.showCode {
Color.black.opacity(0.7)
.transition(AnyTransition.opacity.animation(.default))
}
Button("Demo") { self.showCode.toggle() }
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
The functionality that you are trying to implement is already part of the Animation and Transition modifiers from SwiftUI.您尝试实现的功能已经是 Animation 和 SwiftUI 中的 Transition 修饰符的一部分。
Therefore, you can add .transition
modifier to any of your Views
and it will animate its insertion and removal.因此,您可以将
.transition
修饰符添加到您的任何Views
中,它将为其插入和删除设置动画。
if self.showCode {
Color.black.opacity(0.7)
.transition(AnyTransition.opacity.animation(.easeInOut(duration: 0.5)))
}
You can use a multitude of different transitions like .slide
, .scale
, .offset
, etc. More information about transitionshere .您可以使用多种不同的过渡,例如
.slide
、 .scale
、 .offset
等。有关过渡的更多信息请点击此处。
You can even create custom transitions with different actions for insertion and removal.您甚至可以使用不同的插入和删除操作创建自定义转换。 In your case, different animation curves.
在您的情况下,不同的 animation 曲线。
extension AnyTransition {
static var fadeTransition: AnyTransition {
.asymmetric(
insertion: AnyTransition.opacity.animation(.easeIn(duration: 0.5)),
removal: AnyTransition.opacity.animation(.easeOut(duration: 0.5))
)
}
}
And use it like this:并像这样使用它:
if self.showCode {
Color.black.opacity(0.7)
.transition(.fadeTransition)
}
Hope this helps !希望这可以帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.