sakura-bloom
sakura-bloom

Reputation: 4594

MainPage and navigation setup: iOS and Android

When I create a new Xamarin.Forms app in Visual Studio on Mac, the default template comes with the following code in the App class.

public partial class App : Application
{
    public static bool UseMockDataStore = true;
    public static string BackendUrl = "https://localhost:5000";

    public App()
    {
        InitializeComponent();

        if (UseMockDataStore)
            DependencyService.Register<MockDataStore>();
        else
            DependencyService.Register<CloudDataStore>();

        // What is the reason for this if statement?
        if (Device.RuntimePlatform == Device.iOS)
            MainPage = new MainPage();
        else
            MainPage = new NavigationPage(new MainPage());
    }
}

In the above code what is the reason for the last if statement? Is it because of some differences between iOS and Android and how each handles navigation? Could someone explain please?

Upvotes: 0

Views: 73

Answers (1)

Umair M
Umair M

Reputation: 10720

If you look in MainPage.cs, It is a TabbedPage and while adding content pages as tabs there is another Device.RuntimePlatform check. In case of iOS pages are added as navigation pages. Whereas in case of Android pages are added normally.

public MainPage()
{
    Page itemsPage, aboutPage = null;

    switch (Device.RuntimePlatform)
    {
        case Device.iOS:
            itemsPage = new NavigationPage(new ItemsPage())
            {
                Title = "Browse"
            };

            aboutPage = new NavigationPage(new AboutPage())
            {
                Title = "About"
            };
            itemsPage.Icon = "tab_feed.png";
            aboutPage.Icon = "tab_about.png";
            break;
        default:
            itemsPage = new ItemsPage()
            {
                Title = "Browse"
            };

            aboutPage = new AboutPage()
            {
                Title = "About"
            };
            break;
    }

    Children.Add(itemsPage);
    Children.Add(aboutPage);

    Title = Children[0].Title;
}

This results in following navigation stack structure:

iOS: MainPage -> NavigationPageRoot (ChildPages) -> OtherPages

Android NavigationPageRoot(MainPage) -> ChildPages -> OtherPages

Now this difference in structure is due to difference in native implementation of tabbed page. iOS considers tab pages as Navigation root however in Android tab pages are just children of Navigation root.

This will portray similar navigation behaviour in both platforms even though the page structure is different.

Note: This might only be for tabbed page.

Hope this helps.

Upvotes: 1

Related Questions