我有一个 sliderValueChange
函数可以更新 UILabel
的文本。我希望它有一个时间限制,直到它清除标签的文本,但我也希望在 UISlider
之前的时间限制内移动时取消并重新启动或延迟此“定时清除”操作“定时清除” Action 发生。
到目前为止,这是我所拥有的:
let task = DispatchWorkItem {
consoleLabel.text = ""
}
func volumeSliderValueChange(sender: UISlider) {
task.cancel()
let senderValue = String(format: "%.2f", sender.value)
consoleLabel.text = "Volume: \(senderValue)"
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3, execute: task)
}
显然,这种方法行不通,因为 cancel()
显然无法撤消……(或者至少我不知道如何撤消)。我也不知道如何在这个函数结束时开始一个新任务,如果这个函数被调用,这个任务将被取消..
我是不是用错了方法?有什么我忽略的东西来完成这项工作吗?
最佳答案
使用计时器:
weak var clearTimer: Timer?
和:
override func viewDidLoad() {
super.viewDidLoad()
startClearTimer()
}
func startClearTimer() {
clearTimer = Timer.scheduledTimer(
timeInterval: 3.0,
target: self,
selector: #selector(clearLabel(_:)),
userInfo: nil,
repeats: false)
}
func clearLabel(_ timer: Timer) {
label.text = ""
}
func volumeSliderValueChange(sender: UISlider) {
clearTimer?.invalidate() //Kill the timer
//do whatever you need to do with the slider value
startClearTimer() //Start a new timer
}
关于ios - 如何在 Swift 中取消和重启定时事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173566/