【发布时间】:2020-03-09 18:12:07
【问题描述】:
我正在自学如何编写 Swift 代码,我知道它并不漂亮,但我希望更多地让它首先工作。我知道我需要什么,但我无法弄清楚。我有一个带有一个动作的按钮,当你点击它时,我需要它来改变颜色、标题和功能。我改变了颜色和标题,但改变功能很难。似乎我需要将一个新函数传递给计时器内的“startTapped”函数,但我想不出一个好方法。它可能与 loadView() 的生命周期有关
timerView.actionButton.addTarget(self, action: #selector(startTapped), for: .touchUpInside)
这里是完整的代码 sn-p:
view = timerView
timerView.installContraints()
timerView.actionButton.addTarget(self, action: #selector(startTapped), for: .touchUpInside)
}
@objc func startTapped() {
print("button pressed")
activeTimer?.invalidate()
let startDate = Date()
activeTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in
let currentDate = Date()
let duration = currentDate.timeIntervalSince(startDate)
func formatDuration(DoubleDuration: (Double) -> String) {
// make number formatter function to format the TimeInterval Double into a String??
}
self.timerView.timerLabel.text = "\(duration)"
})
timerView.actionButton.setTitle("STOP", for: .normal)
timerView.actionButton.setTitleColor(.white, for: .normal)
timerView.actionButton.backgroundColor = .red
}
func stopTapped() {
print("stop tapped")
activeTimer?.invalidate()
}
func resetTapped() {
print("something")
} ```
【问题讨论】:
-
“改变功能”是什么意思? :)
-
你需要写一个小状态机。之后就很简单了。