如何使用SwiftUI为包装在视图中的数字设置动画?

时间:2020-04-07 07:40:01

标签: ios swift swiftui

假设我有一个简单的视图,而另一个视图中有一个数字:

struct ContentView: View {
    @State private var counter = 0
    var body: some View {
        VStack {
            Button(action: { self.counter += 1 }) {
                Text("Add 1")
            }
            NumberView(currentValue: counter)
        }
    }
}

struct NumberView: View {
    var currentValue: Int

    var body: some View {
        VStack {
            Text("I don't want to be animated")
            Text(currentValue.description)
                .font(.largeTitle)
                .foregroundColor(Color.black)
                .padding(.all)
        }
     }
}

对于每次点击,我希望数字增加一秒钟,然后像往常一样返回。 (使用缩放效果)。我如何动画化这种缩放比例一秒钟?

2 个答案:

答案 0 :(得分:1)

尝试一下:

struct ContentView: View {
    @State private var counter = 0

    @State var scale = false

    var body: some View {
        VStack {
            Button(action: {
                self.counter += 1
                withAnimation(Animation.easeInOut(duration: 0.5))  {
                    self.scale.toggle()
                    Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { (timer) in
                        withAnimation(Animation.easeInOut(duration: 0.5))  {
                            self.scale.toggle()
                        }
                    }
                }
            }) {
                Text("Add 1")
            }
            NumberView(currentValue: counter)
                .scaleEffect(scale ? 1.5 : 1)
        }
    }
}

struct NumberView: View {
    var currentValue: Int

    var body: some View {
        Text(currentValue.description)
            .font(.largeTitle)
            .foregroundColor(Color.black)
            .padding(.all)
    }
}

答案 1 :(得分:1)

好,这是您已更改要求的新答案

@JoinColumn