美文网首页
SwiftUI Timer 计时器 暂停 开始

SwiftUI Timer 计时器 暂停 开始

作者: fordG | 来源:发表于2020-12-12 14:01 被阅读0次
import SwiftUI
import Combine

class TimeHelp {
    
    var canceller: AnyCancellable?
        
    //每次都新建一个计时器
    func start(receiveValue: @escaping (() -> Void)) {
        let timerPublisher = Timer
            .publish(every: 1, on: .main, in: .common)
            .autoconnect()
        
        self.canceller = timerPublisher.sink { date in
            receiveValue()
        }
    }
    
    //暂停销毁计时器
    func stop() {
        canceller?.cancel()
        canceller = nil
    }
}

struct CountDownView: View {
    @State private var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common)
    
    @State private var second = 10
    private let timeHelper = TimeHelp()
    @State private var end = true
    
    var body: some View {
        
        VStack{
            Text("\(second)")
            Button("begin") {
                guard self.end else {return}
                self.end = false
                self.second = 10
                self.timeHelper.start {
                    print(second)
                    if self.second > 0 {
                        _ = self.second -= 1
                    }else{
                        //暂停
                        self.end = true
                        self.timeHelper.stop()
                    }
                }
            }
            Button("end") {
                guard !self.end else {return}
                self.second = 10
                self.end = true
                self.timeHelper.stop()
            }
        }
        
        .navigationBarTitle(Text("CountDown"), displayMode: .inline)
    }
}

struct CountDownView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView{
            CountDownView()
        }
    }
}

相关文章

网友评论

      本文标题:SwiftUI Timer 计时器 暂停 开始

      本文链接:https://www.haomeiwen.com/subject/ropjgktx.html