iOS: isMovingToParentViewController is not working as expected

荒凉一梦 提交于 2019-12-05 02:12:30

Unfortunately, isMovingToParentViewController isn't true for the root view controller, so I usually handle this situation with a BOOL,

@implementation ViewController {
    BOOL isFirstAppearance;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isFirstAppearance = YES;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (isFirstAppearance) {
        NSLog(@"root view controller is moving to parent");
        isFirstAppearance = NO;
    }else{
        NSLog(@"root view controller, not moving to parent");
    }
}

A simple solution is by adding a flag on viewWillDisappear setting it to YES if the VC1 has been disappeared. Else the view has never been disappeared so it is the first push (RootViewController of Navigation Controller).

Example Code

BOOL hasDisappeared;

-(void)viewWillAppear:(BOOL)animated
{
    if (hasDisappeared==YES) {
        //VC2 has been popped
    }
    else
    {
        //VC1 is the rootViewController
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    //Pushing to VC2
    hasDisappeared=YES;
}

Since it appears that isMovingToParentViewController is only set when a viewController is being pushed to the navigation stack, and not set for the initial rootViewController, I'd suggest using the following:

 if([self.navigationController.viewControllers containsObject:self])
 {
     // being popped to self here
 }
 else
 {
     // being pushed here
 }

You have to check isMovingFromParentViewController in VC2’s viewWillDissapear and call a delegate method implemented in VC1. I.e. VC2 is being removed from its parent nav controller because of being popped.

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