ios - 如何在 Swift 中取消和重启定时事件?

标签 ios swift events delay cancellation

我有一个 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/

相关文章:

ios - 为什么 UIButton 在以编程方式调用其处理程序时不更改其图像?

ios - 播放完 Swift 后关闭视频

iOS:在锁定屏幕上使用控件时,AVPlayer 会播放多个音频实例

ios - 在 NSPredicate 中使用正则表达式执行 NSFetchRequest

events - Powershell事件转发

ios - 将 1347616929 转换成 dd/MM/yyyy hh :mm:ss format

ios - 在 Swift 中,我有 2 个导航栏,但想隐藏其中一个,怎么办?

ios - swift2 中的委托(delegate)错误

php - Magento 在保存客户地址时会发送事件吗?

c# - 取消 ListBox SelectedIndexChange 事件