import SwiftUI
struct ContentView: View {
@State var timeRemaining = 100
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@State var isActive = true
var body: some View {
ZStack {
Image("background").resizable().scaledToFill().edgesIgnoringSafeArea(.all)
VStack {
Text("Time:\(timeRemaining)").font(.largeTitle)
.foregroundColor(.white).padding(.horizontal, 20).padding(.vertical, 5)
.background(Capsule().fill(Color.black).opacity(0.8))
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification), perform: { _ in
isActive = false
})
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification), perform: { _ in
isActive = true
})
}
}.onReceive(timer, perform: { time in
guard self.isActive else {return}
if timeRemaining > 0 {
timeRemaining -= 1
}
})
}
}
SwiftUI:Timer Remaining
最新推荐文章于 2023-08-09 19:40:56 发布