Adeptus Mechanicus
Adeptus Mechanicus

Reputation: 171

How to go back to previous ViewController in Xamarin.IOS

I make an app in VisualStudio Xamarin (not Xamarin.Forms) with two view controller. First view controller is list of items, second contain item's detail info. When user tap item in list, second view opens with code

DetailViewController detailController = this.Storyboard.InstantiateViewController("DetailViewController") as DetailViewController;
detailController._idx = idx;
this.NavigationController.PushViewController(detailController, true);

But I don't know how to go back to first ViewController programmatically - for example there are button "Go Back" on DetailViewController I try to use this code:

backButton.TouchUpInside += (s,e) => {
  this.NavigationController.DismissViewController(true, null)
};

But it doesn't give any result. Can anybody help me with this?

UPDATED

I changed code to:

backButton.TouchUpInside += (s,e) => {
  this.NavigationController.DismissViewController(true, async () => { await DismissViewControllerAsync(true); });
  ListViewController listController = this.Storyboard.InstantiateViewController("ListViewController ") as ListViewController;
  this.NavigationController.PresentViewController(listController, true, null);
} 

This work for "Go back", but when I try to choose same or another item in list and open new DetailViewController, it throw exception "System.NullReferenceException: Object reference not set to an instance of an object" on

this.NavigationController.PushViewController(detailController, true);

(In details - I run app, ListViewController opens, I choose item1, DetailViewController opens, I tap BackButton, ListViewController opens, I chhose any item, Exception)

Upvotes: 1

Views: 4005

Answers (2)

ColeX
ColeX

Reputation: 14475

You got Push,Pop and Present,Dismiss mixed up.

When the viewcontroller is put inside Navigation, you should use push and pop to control the stack.

Modify your code :

backButton.TouchUpInside += (s,e) => {
  this.NavigationController.PopViewController(true); 
} 

Refer to

Presenting a View Controller

UINavigationController

Upvotes: 6

Troels Thisted
Troels Thisted

Reputation: 76

If you need a "back" butten to apear automatically then you need to start with a navigation controller, and from there open a viewcontroller...

See more at this link: https://developer.xamarin.com/guides/ios/getting_started/hello,_iOS_multiscreen/hello,_iOS_multiscreen_quickstart/

otherwise you need to make a butten and simply just use the samee method as before!

Ask if you don't understand it!

Upvotes: 0

Related Questions