首页 > 解决方案 > 如何快速防止 UIViewController 的多次推送?

问题描述

当我在下一个按钮上快速点击多次时,控制器会更清晰地堆叠多次,问题是我们需要多次单击后退按钮才能到达前一个屏幕。

下一个按钮代码

guard  let controller = UIStoryboard(name: "Filepreview", bundle: nil).instantiateViewController(withIdentifier: "FilepreviewVC") as? PreviewFileViewController else {return}
                            self.navigationController?.pushViewController(controller, animated: true)

标签: iosswiftnavigation

解决方案


不允许用户多次按下按钮!

这可以通过在按下新 VC 之前禁用按钮来完成:

nextButton.isEnabled = false

如果您不希望用户看到按钮被禁用,或者推送的触发器不是可以禁用的,只需使用私有属性来跟踪您自己的“禁用”状态:

private var nextButtonDisabled = false

// ...

// when you want to push the new VC, check nextButtonDisabled first!
if nextButtonDisabled {
    return
}
nextButtonDisabled = false
// push new VC here

当用户导航回来时,viewDidAppear将被调用,因此您可以启用nextButtonin viewDidAppear

nextButton.isEnabled = true
// or
nextButtonDisabled = false

或者,在navigationController(_:didShow:animated:)委托方法中执行此操作。

self.navigationController?.delegate = self

// ...

extension MyViewController : UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        if viewController == self {
            nextButtonDisabled = false
        }
    }
}

推荐阅读