Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

popToRootViewController not working when sending from add screen

Tags:

ios

swift

segue

I have a simple app I am building. A list of items in 1 view controller with a table view and embedded navigation controller. When you select a row it brings you to the details screen (no problem).

Push from List View to List Item

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "ListItemDetailsVC", sender: nil)
}

Pop back from list item to List View

@IBAction func backToInboxTapped(_ sender: Any) {
    navigationController?.popToRootViewController(animated: true)
}

This works fine!

My issue is that I have another view controller (add item) that presents modally when add button is clicked. The idea is that when it saves it brings you to the list detail vc.

@IBAction func saveItem(_ sender: Any) {
    performSegue(withIdentifier: "DetailsFromAdd", sender: nil)
}

Opening up the details view controller from the add new controller works fine but once I open the details view I want to be able to go back to the rootViewController. The button does not work anymore

enter image description here

like image 298
user934902 Avatar asked Nov 08 '16 10:11

user934902


1 Answers

In your case you should not need to use segue. You have to clear some concepts.

You can't popToRootViewController or VC if you have pushed or show view controller from modally presented vc!!

Now if you want to achieve this then you have to make some changes that I am trying to mention below :

take one global variable or property (objective c concept) in your add item VC. now when you come to add item VC from lust VC set this global variable or property to self something like,

   AddListItemVC *advc = [self.storyboard instantiateViewControllerWithIdentifier:@"addListItem"];  // addListItem is storyboard id for viewcontroller




[self presentViewController:advc animated:NO completion:^{


    advc.vc = self;  // here vc is the propery of type `UIVIewController` declare in AddListItemVC

}];

Now your code for going to details VC from add list VC should be like,

    DetailListViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"detailViewScreen"];   // detailViewScreen is storyboard id which you can set from identity inspector



[self dismissViewControllerAnimated:NO completion:^{


    [self.vc.navigationController pushViewController:dvc animated:YES];  // here self.vc is global variable or property that contains reference of first VC (i.e. list view controller)


}];

no need to use performsegue in this case. You can use performsegue to go in detailvc directly from firstvc i mean from list vc.

Hope you got understand concept and i have written objective c snippet because of lake of time!! hope you can easily convert to swift!!

like image 200
Ketan Parmar Avatar answered Oct 16 '22 02:10

Ketan Parmar