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()
}
}
}
网友评论