我正在使用NSTimer构建倒数计时器,我使用两个按钮来增加和减少时间。我希望能够在增加或减少时间时将倒数计时器秒数设置为00。因此,例如,假设计时器是在10:42,我按下减少按钮,一旦它应该到10:00而不是9:42。我怎么能这样做?这是我目前用来增加和减少时间的代码:
var timeCount:TimeInterval = 1800 //seconds
func startTimer() {
focusTimer.position = CGPoint(x: self.size.width / 2, y: self.size.height / 1.5)
focusTimer.fontName = "Helvetica"
focusTimer.text = "30 00"
focusTimer.fontColor = UIColor.white
focusTimer.fontSize = 50
focusTimer.zPosition = 79
focusTimer.name = "focustimer"
addChild(focusTimer)
}
func timeStringForScore3(_ time:TimeInterval) -> String {
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i %02i", minutes, seconds)
}
func updateStopWatch3() {
self.timeCount -= 1
focusTimer.text = timeStringForScore3(timeCount)
}
@discardableResult
func nextMinute(after seconds: TimeInterval) -> TimeInterval {
return (seconds/60 + 1).rounded(.down) * 60
}
@discardableResult
func previousMinute(before seconds: TimeInterval) -> TimeInterval {
return (seconds/60 - 1).rounded(.up) * 60
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
if node.name == "increase" {
nextMinute(after: timeCount)
focusTimer.text = timeStringForScore3(timeCount)
}
if node.name == "decrease" {
previousMinute(before: timeCount)
focusTimer.text = timeStringForScore3(timeCount)
}
答案 0 :(得分:1)
试试这个:
if node.name == "increase" {
timeCount = timeCount + (60 - (timeCount % 60))
focusTimer.text = timeStringForScore3(timeCount)
}
if node.name == "decrease" {
timeCount = timeCount - (timeCount % 60)
focusTimer.text = timeStringForScore3(timeCount)
}
答案 1 :(得分:1)
要将值增加到下一整分钟,您可以按以下步骤操作:
相应地减少工作:
func nextMinute(after seconds: TimeInterval) -> TimeInterval {
return (seconds/60 + 1).rounded(.down) * 60
}
func previousMinute(before seconds: TimeInterval) -> TimeInterval {
return (seconds/60 - 1).rounded(.up) * 60
}
测试用例:
nextMinute(after: 1800.0) // 1860
nextMinute(after: 1800.1) // 1860
nextMinute(after: 1799.9) // 1800
nextMinute(after: 0.0) // 60
nextMinute(after: -15.0) // 0
nextMinute(after: -60.0) // 0
nextMinute(after: -61.0) // -60
previousMinute(before: 1800.0) // 1740
previousMinute(before: 1800.1) // 1800
previousMinute(before: 1799.9) // 1740
previousMinute(before: 0.0) // -60
previousMinute(before: -15.0) // -60
previousMinute(before: -60.0) // -120
previousMinute(before: -61.0) // -120