Skip swift ViewController主要功能如viewDidDisappear

时间:2018-01-22 11:09:20

标签: ios swift function view

在我的代码中,当视图消失时,会发生特定操作。我是通过viewDidDisappear()函数完成的。 我有一个特定的按钮,当按下时它会转到另一个视图。我想知道我只能通过特定按钮跳过viewDidDisappear()所导致的功能。

我完全知道我可以添加一种' if' viewDidDisappear()中的陈述,但我想知道是否有更有效的方法。

2 个答案:

答案 0 :(得分:4)

viewDidDisappear()是一个UIViewController生命周期回调方法,由环境调用 - 据我所知,没有办法禁用它的调用。而且我认为不应该 - 正如我所提到的那样,它是UIViewController生命周期的一部分,而不是称它会破坏合同 - 请参阅documentation

enter image description here

因此,您必须(并且应该)使用if语句来实现您想要的目标。

做这样的事情:

fileprivate var skipDisappearingAnimation = false

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)

    prepareInterfaceForDisappearing()
}

fileprivate func prepareInterfaceForDisappearing() {
    guard !skipDisappearingAnimation else {
        // reset each time
        skipDisappearingAnimation = false
        return
    }

    // do the stuff you normally need
}

@objc fileprivate func buttonPressed(_ sender: UIButton) {
    skipDisappearingAnimation = true
    // navigate forward
}

答案 1 :(得分:0)

无法做到;您必须使用if手动处理案例,例如:

    var shouldSkip: Bool = false

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if !shouldSkip {
            // your code goes here
        }
        shouldSkip = false // don't forget to set should skip to false again
    } 

    @IBAction func buttonDidTap(_ sender: Any) {
        shouldSkip = true // this will avoid run your code
        // your code here
    }