ios - 用户再次单击按钮时如何推迟隐藏视图?
问题描述
如果用户单击按钮,我会在 3 秒后使用DispatchQueue.main.asyncAfter
. 但是,如果用户再次单击该按钮,我不想将隐藏活动推迟 3 秒以上,因此之前的隐藏调用将被忽略。
我尝试了以下代码,但它在前 3 秒后隐藏了视图。
class MyView: UIView {
private var hideControls: DispatchWorkItem?
func displayControls() {
isHidden = false
hideControls?.cancel()
hideControls = DispatchWorkItem {
print("displayControls: DispatchWorkItem called ")
self.isHidden = true
}
if let hideControls = hideControls {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: hideControls)
}
}
}
解决方案
如果您想忽略之前的工作,您可以使用 Timer,添加属性 timer,
var timer : Timer?
并在您的隐藏方法上使用它。
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: false, block: {[weak self] (_) in
#add the action that you want
self?.isHidden = true
})
兄弟。
推荐阅读
- javascript - 如何在 Javascript 中同时渲染和更新多个计时器?
- java - 如何忽略@OneToMany 上的字段
- r - 在带有 r 的向量中找到局部最小值
- gcp-ai-platform-notebook - 如何强制 docker pull 从 Google AI Platform Notebooks 的自定义图像中提取?
- python - 从 numpy.int32 数组的数据字节中有效地删除每 4 个字节
- django - 未找到带有参数 '('',)' 的 'add_to_cart' 的反向操作。尝试了 1 种模式:['cart/add/(?P
[^/]+)/$'] - python - 如何在pyspark sql python中加入2个DataFrame
- python - pywintypes.error: (2, 'BeginUpdateResource')
- c - 无法理解 C 输出
- python - 在烧瓶应用程序中正确使用 g