특정 날짜부터 현재 날짜까지 카운트 다운하는 타이머가 있지만 문제는 00:00:00에 도달해도 타이머가 중지되지 않는다는 것입니다.
이 튜토리얼을 따랐습니다
@State var currentDate: Date = Date()
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (_) in
self.currentDate = Date()
}
}
var endDate = Calendar.current.date(byAdding: .minute, value: 1, to: Date())!
var body: some View {
Text(countdownString(to: endDate))
.font(.headline)
.fontWeight(.bold)
.foregroundColor(.green)
.onAppear {
_ = self.timer
if self.endDate == self.currentDate {
self.timer.invalidate()
}
}
}
func countdownString(to date: Date) -> String {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.hour, .minute, .second], from: currentDate, to: endDate)
return String(format: "%02d hours : %02d minutes : %02d seconds",
components.hour ?? 00,
components.minute ?? 00,
components.second ?? 00)
}
에서 타이머를 설정 onAppear
하고 무효화 timer
할 때 endDate
와 currentDate
정렬 함께합니다.
struct CV: View {
@State var currentDate: Date = Date()
@State var timer: Timer?
var endDate = Calendar.current.date(byAdding: .minute, value: 1, to: Date())!
var body: some View {
Text(countdownString(to: endDate))
.font(.headline)
.fontWeight(.bold)
.foregroundColor(.green)
.onAppear {
self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
self.currentDate = Date()
}
}
}
func countdownString(to date: Date) -> String {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.hour, .minute, .second], from: currentDate, to: endDate)
if currentDate >= endDate {
timer?.invalidate()
timer = nil
}
return String(format: "%02d hours : %02d minutes : %02d seconds",
components.hour ?? 00,
components.minute ?? 00,
components.second ?? 00)
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다