首页 > 解决方案 > 用户再次单击按钮时如何推迟隐藏视图?

问题描述

如果用户单击按钮,我会在 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)
            }
        }
    }

标签: iosswift

解决方案


如果您想忽略之前的工作,您可以使用 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
        })

兄弟。


推荐阅读