我在iOS课程中创建了一个简单的秒表应用。完成后,我意识到它没有做任何重要的事情,它没有在后台运行。
这怎么办?我在这个主题上进行了很多搜索,但是找不到正确的答案。
任何想法都值得赞赏。下面的代码是目前集成在应用程序中的代码。
var timer: Timer!
var minutes = 0
var seconds = 0
var fractions = 0
var lapArray: [String]? = []// to track the laps
var addLap = false
var counterString = ""
var isStarted = false
//MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
makeStatusBarWhite()
configureInterface()
timeLabel.text = "00:00.00"
}
func configureInterface() {
startButton.layer.cornerRadius = startButton.frame.size.height/2
lapButton.layer.cornerRadius = startButton.frame.size.height/2
}
@objc func timeDidIncrease() {
fractions += 1
if fractions == 100 {
seconds += 1
fractions = 0
}
if seconds == 60 {
minutes += 1
seconds = 0
}
let fractionsString = fractions > 9 ? "\(fractions)" : "0\(fractions)"
let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"
counterString = "\(minutesString):\(secondsString).\(fractionsString)"
timeLabel.text = counterString
}
func configureAndStartTimer() {
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timeDidIncrease) , userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoop.Mode.common) //timer will not be affected by UI interaction
}
//MARK: - Actions
@IBAction func didTapLap(_ sender: Any) {
if isStarted {
lapArray?.insert(timeLabel.text!, at:0)
}else {
timeLabel.text = "00:00.00"
fractions = 0
minutes = 0
seconds = 0
timer.invalidate()
lapArray?.removeAll()
resetStartButton()
lapButton.setTitle("Lap", for: .normal)
lapButton.isUserInteractionEnabled = false
lapButton.alpha = 0.3
}
lapsTableView.reloadData()
}