SwiftUI:完成后将视图比例动画恢复到初始状态?

问题描述 投票:0回答:2

我有这个简单的观点:

struct ContentView: View {
    
    @State private var scale:Double = 1
    
    var body: some View {
        
        Rectangle()
            .fill(.red)
            .frame(width: 200, height: 200)
            .scaleEffect(scale)
            .animation(Animation.easeInOut(duration: 1).repeatCount(4, autoreverses: true).delay(1), value: scale)
            .onAppear {
                scale = 1.2
            }

    }
    
}

它产生这个动画:

您会注意到在动画结束时它会捕捉到比例 1.2,因为这是后面的状态比例效果的值。

我想触发出现的缩放动画,并使其从状态 1 到 1.2 并返回“脉冲”4 次,4 次。现在它确实以 1 级脉冲开始,但最后它会突然变为 1.2。我该如何解决这个问题,以便它创建一个从 1 开始、缩放到 1.2 并返回 4 倍的“脉冲”动画?

ios animation swiftui
2个回答
1
投票

供将来参考,在 iOS 17 中,

withAnimation()
函数现在包含一个在动画完成时执行的完成回调。

考虑到前面的场景,您应该在动画结束时将视图返回到其初始状态。由于您需要四次重复,因此需要从完成回调中减去一次重复,因为它将在动画完成一次后调用。这是修改后的代码:

struct ContentView: View {
    @State private var scale: Double = 1

    var body: some View {
        Rectangle()
            .fill(.red)
            .frame(width: 200, height: 200)
            .scaleEffect(scale)
            .onAppear {
                withAnimation(Animation.easeInOut(duration: 1).repeatCount(3, autoreverses: true).delay(1)) {
                    scale = 1.2
                } completion: {
                    withAnimation(Animation.easeInOut(duration: 1)) {
                        scale = 1
                    }
                }
            }
    }
}

结果:


0
投票

为了获得更流畅的动画,请在延迟结束之前启动回到初始状态动画:

@State private var scale = 1.0
@State private var favorite = false
var body: some View {
        Button {
            withAnimation(Animation.easeInOut(duration: 0.2)) {
                scale = 2
                favorite.toggle()
                withAnimation(Animation.easeInOut(duration: 0.2).delay(0.2)) {
                    scale = 1
                }
            } 
        }
        label: {
            Image(systemName: favorite ? "star.fill" : "star")
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.