Search code examples
c#iosxamarin.iosuinavigationcontrollerrootviewcontroller

How to open NavigationController's root and pass a value?


I am creating the login part of a Xamarin.iOS application. When logging in I want to pass an User Object to the ProjectsViewController. First a user enters the username and password, then it is validated and lastly, once it is validated I want to go to the main screen which is called ProjectsViewController.

Storyboard

//first get user from Restful service 
var response = await apiService.GetUserByToken("http://192.168.1.20:55405",
            "/api",
            "/Account/FullUser",
            token.TokenType,
            token.AccessToken);
        //get User object
        var user = (User)response.Result;
        user.Password = password;
        if (response.IsSuccess)
        {
            //loguser is the User object that will be passed to the root
            logUser = user;
        }            

        //get storyboard 
        UIStoryboard board = UIStoryboard.FromName("Main", null);
        ProjectsViewController ctrl = (ProjectsViewController)board.InstantiateViewController("projectsViewController");
        //current user is the propery that I want to access in the next screen
        ctrl.CurrentUser = logUser;
        ctrl.ModalTransitionStyle = UIModalTransitionStyle.CoverVertical;

        UINavigationController nav = (UINavigationController)board.InstantiateViewController("navController");
        nav.ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve;
        //this sends me to the root but the object is not passed
        PresentViewController(nav, true, null);

The code so far validates the user and sends me to the root screen, but the object is not passed. Please help! thanks in advance!


Solution

  • The thing is that you are creating a new instance of the: ProjectsViewController and setting its CurrentUser, but you are not showing that controller at all.

    What you should do is:

    UINavigationController nav = (UINavigationController)board.InstantiateViewController("navController");
    nav.ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve;
    //New code
    var projectVC = (ProjectsViewController)nav.ViewControllers.FirstOrDefault();
    projectVC.CurrentUser = logUser;
    
    PresentViewController(nav, true, null);
    

    Since when you instantiate the: "navController" from storyboard it will also instantiate its ProjectsViewController, which is in its ViewControllers list.