我需要将字符串转换为Int,以便我可以使用if>语句所以我可以启用和禁用按钮。正如您在updateStopwatch中的注释行中所看到的,我尝试了多种转换方式,但没有取得任何成功
我的班级看起来像
class Stopwatch {
var startTime:Date?
func startTimer() {
startTime = Date();
}
func elapsedTimeSinceStart() -> String {
var elapsed = 0.0;
if let elapsedTime = startTime {
if firstHalfTime {
elapsed = elapsedTime.timeIntervalSinceNow
} else {
elapsed = elapsedTime.timeIntervalSinceNow - 45*60
}
}
elapsed = -elapsed
let minutes = Int(floor((elapsed / 60)));
let seconds = Int(floor((elapsed.truncatingRemainder(dividingBy: 60))));
// print(elapsed)
let timeString = String(format: "%02d:%02d", minutes, seconds)
// print(timeString)
return timeString
}
}
我的更新计时器功能
func updateStopwatch() {
let stopWatchString = stopWatch.elapsedTimeSinceStart()
stopwatchLabel.text = stopWatchString
// let minutesString:Int = Int(stopWatchString)!
// minutes = minutesString
if minutes > 1 {
endFirstHalf.isEnabled = true
self.endFirstHalf.alpha = 1
}
}
答案 0 :(得分:1)
插入冒号(:)后,您无法将字符串转换回Int
。
我建议您返回TimeInterval
func elapsedTimeSinceStart() -> TimeInterval {
var elapsed = 0.0
if let elapsedTime = startTime {
if firstHalfTime {
elapsed = elapsedTime.timeIntervalSinceNow
} else {
elapsed = elapsedTime.timeIntervalSinceNow - 45*60
}
}
elapsed = -elapsed
return elapsed
}
并在updateStopwatch()
func updateStopwatch() {
let elapsed = stopWatch.elapsedTimeSinceStart()
let minutes = Int(floor(elapsed / 60)));
let seconds = Int(floor((elapsed.truncatingRemainder(dividingBy: 60))));
let stopWatchString = String(format: "%02d:%02d", minutes, seconds)
stopwatchLabel.text = stopWatchString
if minutes > 1 {
endFirstHalf.isEnabled = true
self.endFirstHalf.alpha = 1
}
}
此代码执行相同但使用更现代的API
let dateComponentsFormatter : DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second]
return formatter
}()
func elapsedTimeSinceStart() -> DateComponents {
var components = DateComponents(minute: 0, second:0)
if let elapsedTime = startTime {
components = Calendar.current.dateComponents([.minute, .second], from: elapsedTime, to: Date())
if !firstHalfTime { components.minute! += 45 }
}
return components
}
func updateStopwatch() {
let components = elapsedTimeSinceStart()
stopwatchLabel.text = dateComponentsFormatter.string(from: components)
if components.minute! > 1 {
endFirstHalf.isEnabled = true
self.endFirstHalf.alpha = 1
}
}