Zack
Zack

Reputation: 1617

Detecting when a view controller is visible

The Situation

Let's say that I have 2 view controllers inside a navigation controller. Inside the storyboard, they would look like:

NC -> VC1 -> VC2

NC: Navigation controller

VC1: View controller one

VC2: View controller 2

So VC1 is the root view controller of the navigation controller, and VC1 is connected to VC2 via a show segue.

What must happen:

VC1 must call a function every time it opens, (e.g necessaryFunction()). It currently calls this function in viewDidLoad(). The problem is that when the user presses the back button in VC2 (the one on the navigation bar) and VC1 is now showing, viewDidLoad() is not called. This means that necessaryFunction() will not be called either.

What I am looking for:

I am looking for a way to make sure that necessaryFunction() is called when returning to VC1 from VC2. I understand that this could be solved with a delegate, but that seems overly complicated for such a simple thing, surely there is another way to do this.

Maybe I could put necessaryFunction() into viewWillAppear(), but I don't think this would work.

By the way: I am coding in Swift.

EDIT: I have found this post: iOS how to detect programmatically when top view controller is popped?, but it is for objective-C, not swift.

Upvotes: 1

Views: 3260

Answers (1)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

These four methods can be used in a view controller's appearance callbacks to determine if it is being

presented, dismissed, or added or removed as a child view controller.

@available(iOS 5.0, *)
open var isBeingPresented: Bool { get }

@available(iOS 5.0, *)
open var isBeingDismissed: Bool { get }


@available(iOS 5.0, *)
open var isMovingToParentViewController: Bool { get }

@available(iOS 5.0, *)
open var isMovingFromParentViewController: Bool { get }

For example, a view controller can

check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:

method by checking the expression

([self isBeingDismissed] || [self isMovingFromParentViewController]).

for e.g , you can call the method as

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if (self.isMovingFromParentViewController())  {
        // we're already on the navigation stack
        // another controller must have been popped off
    }


}

Upvotes: 2

Related Questions