简体   繁体   中英

How to determine that UIViewController was started for the first time?

I have a ViewControllers hierarchy, with UINavigationViewController as the root.
How can I find out whether some ViewController was started for the first time or it was started as a result of unwinding of the navigation stack?

Assuming you wish to know if viewWillAppear: (or viewDidAppear: ) is being called when the view controller is first being displayed or if it's being displayed because another view controller has been dismissed, you can easily do the following:

Newer Swift versions:

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

    if isBeingPresented || isMovingToParent {
        // This is the first time this instance of the view controller will appear
    } else {
        // This controller is appearing because another was just dismissed
    }
}

Older Swift versions:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    if isBeingPresented() || isMovingToParentViewController() {
        // This is the first time this instance of the view controller will appear
    } else {
        // This controller is appearing because another was just dismissed
    }
}

when you push new viewcontroller on your navigation stack, it is instantiate first time, and when you pop it out from stack it is dealloc or released. so when you push or go forward then it is first time but when you come back to any viewcontroller from previous then current vc is already in memory and not first time!!!

On Objective-C it looks like:

-(void) viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    if ([self isBeingPresented] || [self isMovingToParentViewController]) {
        // This is the first time
    } else {
        // This is the NOT first time
    }
}

isBeingPresented and isMovingToParent are tricky one.

My method is to create a counter and increment it in viewWillAppear.

var viewWillAppearCounter = 0

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

    if viewWillAppearCounter == 0 {
        print("viewWillAppear will be executed for the first time")
    } else {
        print("viewWillAppear was already executed \(viewWillAppearCounter) times")
    }
    viewWillAppearCounter += 1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM