循环更新状态时如何显示所有中间视图swiftUI

时间:2019-12-29 23:07:26

标签: swiftui

如何强制视图更新以反映所有@State更改,但不从最初的状态跳到最后的状态?

    import SwiftUI

struct ContentView: View {

    @State var counter = 0

    func updatecounter(){
        for _ in 1...10{withAnimation(.easeInOut(duration: 1)){counter+=1}}
    }

    var body: some View {
        VStack {
            Spacer()
            Text("Counter: \(self.counter)")
            Spacer()
            Button(action: {self.updatecounter()}){Text("Update Counter")}
            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {static var previews: some View {ContentView()}}

我希望上面的代码在单击按钮时显示从1到10的所有数字(1、2、3、4、5 ...),而不是立即从1跳到10会。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以添加Timer发布者以在SwiftUI中制作连续动画:

                   import Combine

          @State var counter = 0
          @State  var cancelable : AnyCancellable?

            func updatecounter(){

                 cancelable   =    Timer.publish(every: 1, on: RunLoop.main, in: RunLoop.Mode.default).autoconnect().sink { (Date) in
                     withAnimation(Animation.easeInOut(duration: 1)){
                        self.counter += 1
                    }
                    if self.counter == 10 {
                              self.cancelable?.cancel() }
                    }
                }