【问题标题】:How Do I Cancel and Restart a Timed Event in Swift?如何在 Swift 中取消和重新启动定时事件?
【发布时间】:2017-08-27 15:59:54
【问题描述】:

我有一个sliderValueChange 函数可以更新UILabel 的文本。我希望它有一个时间限制,直到它清除标签的文本,但我也希望每当 UISlider 在“定时清除”之前的时间限制内移动时,取消并重新启动或延迟这个“定时清除”操作行动发生。

到目前为止,这是我所拥有的:

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() 显然无法逆转..(或者至少我不知道如何)。我也不知道如何在这个函数结束时开始一个新任务,如果函数被调用,它将被取消..

我是不是走错了路?有什么我忽略的东西来完成这项工作吗?

【问题讨论】:

  • 我想要一个 NSTimer。如果要更改计时器周期,您仍然需要取消(无效)并重新安排计时器。但是,如果您确实想使用任务,是的,您需要创建并提交一个新任务。

标签: ios swift events delay cancellation


【解决方案1】:

使用计时器:

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
}

【讨论】:

  • @PlateReverb,在这个答案中,声明是func clearLabel(_ timer: Timer),它使#selector(clearLabel(_:)) 完全有效。另一方面,您的 suggested edit 是错误的,会引入以下错误:error: use of unresolved identifier 'clearLabel(timer:)' selector: #selector(clearLabel(timer:))
  • @Cœur 这很奇怪......因为#selector(clearLabel(_:)) 我收到错误Use of unresolved identifier 'clearLabel' 并将_ 更改为timer 修复它。我之前遇到过类似的问题,并在 SO Q&A 上找到了解决同类问题的方法。我希望我知道为什么会发生这个错误以及为什么这个解决方案对我有用,而不是你......?
  • 哦,@PlateReverb,我只是注意到你做了 两个 建议的编辑。嗯,第一个是正确的。我在批评第二个,其中函数的签名与以前不同:如果您查看历史记录,Duncan 将其从 func clearLabel(timer: Timer) 更改为 func clearLabel(_ timer: Timer)
  • @Cœur 哦!我错过了那个变化。这解释了它。谢谢!
【解决方案2】:

问题是你取消了错误的东西。您不想取消任务;你想取消你说asyncAfter时开始的倒计时

所以使用 DispatchTimer 或 NSTimer(现在在 Swift 中称为 Timer)。这些是可以取消的反击。然后你就可以重新开始数数了。

【讨论】:

    猜你喜欢
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多