0

我需要将字符串转换为 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
        }
    } 
4

1 回答 1

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
    }
}
于 2017-03-11T11:22:12.747 回答