Unwind segue with Navigation back button

风流意气都作罢 提交于 2019-11-28 20:12:22
Alan

In the end I didn't need to unwind the segue since I could still get a reference to the parent controller methods by following the navigation controller.

I was able to get a reference by doing the following in the - (void)viewWillDisappear:(BOOL)animated method of the child controller

NSInteger currentVCIndex = [self.navigationController.viewControllers indexOfObject:self.navigationController.topViewController];

FirstViewController *parent = (FirstViewController *)[self.navigationController.viewControllers objectAtIndex:currentVCIndex];

parent.barcodeType = indexPath.row;

which passed the settings variable back to the original controller perfectly.

I also added an import reference to the parent controller at the top of the childcontroller

@Alan is on the right track. Just add a test to prevent the segue from firing when not going back to the first view controller. Something like this in viewWillDisappear will actually allow you to perform the unwind segue for a back button. You will need to create a manual unwind segue by dragging from the class down to the exit icon. Be sure to name it after you create it.

UIViewController *vc = self.navigationController.topViewController;
if ([FirstViewController class] == [vc class])
{
    [self performSegueWithIdentifier:@"unwindSegue" sender:self];
}

I'd like to add a Swift solution that follows @Chuck H suggestion above:

let rootVC = self.navigationController!.topViewController
if rootVC.isKindOfClass(TheNameOfYourViewController) {
    performSegueWithIdentifier("yourNamedSegueIdentifier", sender: self)
}

An alternative you might have not considered is to make the parent a delegate of the child and use delegate methods in the child to update the parent.

That way you would bypass the need to add to the navigation unwind, because the parent is already up to date the moment you hit back.

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