如何在没有按钮的情况下自动在多个文本视图之间切换

时间:2020-08-28 20:21:02

标签: swiftui

我想自动更改文本。我可以使用切换按钮来使用它,但是我想不使用按钮来执行它。我希望它每3秒保持交替。

这是代码:

struct ContentView: View {
   @State var homeString = true
   var body: some View {
       VStack {
            Text(homeString ? "Welcome." : "How can I help you?").font(.title)
            .animation(.easeInOut(duration:1.0))
          Button(action: {self.shortString.toggle()}) {
            Text("Toggle").padding()
          }
      }
   }
}

1 个答案:

答案 0 :(得分:1)

您可以创建一个计时器,每3秒触发一次并切换homeString

struct ContentView: View {
    @State var homeString = true

    @State var timer: Cancellable?

    var body: some View {
        VStack {
            Text(homeString ? "Welcome." : "How can I help you?")
                .font(.title)
                .animation(.easeInOut(duration: 1.0))
        }
        .onAppear {
            self.timer = Timer.publish(every: 3, on: .main, in: .common)
                .autoconnect()
                .sink(receiveValue: { _ in self.homeString.toggle() })
        }
    }
}

如果您想停止计时器,请致电:

timer?.cancel()