如何在SwiftUI中使用计时器更新文本

时间:2019-06-08 07:28:51

标签: swift alert swiftui

我现在正在查看文本,我想每秒使用一次警报来更新文本。

这是我完成的代码。

struct CountDownView : View {
    var body: some View {       
        VStack{
            Text("Update text with timer").lineLimit(nil).padding(20)

            }.navigationBarTitle(Text("WWDC"), displayMode:.automatic)
    }
}        

3 个答案:

答案 0 :(得分:1)

我设法使用警报来更新文本。

我已将日期声明为struct CountDownView : View { @State var nowDate: Date = Date() let referenceDate: Date var timer: Timer { Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in self.nowDate = Date() } } var body: some View { Text(countDownString(from: referenceDate)) .font(.largeTitle) .onAppear(perform: { _ = self.timer }) } func countDownString(from date: Date) -> String { let calendar = Calendar(identifier: .gregorian) let components = calendar .dateComponents([.day, .hour, .minute, .second], from: nowDate, to: referenceDate) return String(format: "%02dd:%02dh:%02dm:%02ds", components.day ?? 00, components.hour ?? 00, components.minute ?? 00, components.second ?? 00) } } ,因此,使用警报文本更改日期时,也会进行更新。

{{1}}

答案 1 :(得分:1)

使用组合:


struct CurrentDateView : View {
    @State var now = Date()

    let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()

    var body: some View {
        Text("\(now)")
            .onReceive(timer) {
                self.now = Date()
            }
    }
}

答案 2 :(得分:0)

原始样本位于:

https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-a-timer-with-swiftui

我确实使用这种方法从我的一个电话中定期更新...

另见:

https://developer.apple.com/documentation/combine/replacing-foundation-timers-with-timer-publishers

struct ContentView: View {
@State var msg = ""

var body: some View {

    let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()

    Text(msg)
        .onReceive(timer) { input in
            msg = MyManager.shared.ifo ?? "not yet received"
        }
}

}

我确实需要通过其他方式致电网络,但在这里我只是定期致电我的一些经理。

要停止计时器(如来自 hackingSwift 的链接..)您可以使用:

            self.timer.upstream.connect().cancel()