Skip swift ViewController main functions such as viewDidDisappear

為{幸葍}努か 提交于 2020-01-25 07:48:50

问题


In my code, when a view disappears, a specific action occurs. I am doing it through the viewDidDisappear() function. I have a specific button that when is pressed it goes to another view. I was wondering in what I way I could tell ONLY the function caused by a specific button to skip the viewDidDisappear().

I perfectly know I can add a sort of 'if' statement in the viewDidDisappear() but I was wondering if there was a more efficient method.


回答1:


viewDidDisappear() is a UIViewController's lifecycle callback method that's called by the environment - as far as I know there is no way to disable its calling. And I don't think there should be - as I mentioned, it is a part of UIViewController's lifecycle, not calling it would break the contract - see its documentation.

Therefore you have to (and you should) achieve what you want by using if statement.

Do something like this:

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
}



回答2:


It cannot be done; you must handle the case manually with if, something like:

    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
    }


来源:https://stackoverflow.com/questions/48380208/skip-swift-viewcontroller-main-functions-such-as-viewdiddisappear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!