Xamarin iOS PushViewController null引用异常

时间:2017-07-19 21:56:49

标签: ios xamarin xamarin.ios uinavigationcontroller nullreferenceexception

我是Xamarin iOS开发的新手,我遇到了一个我无法弄清楚的问题。当下面一行代码运行时,它会抛出一个空引用异常,我无法弄清楚原因。

this.NavigationController.PushViewController(location, true);

这是我的整个代码块。

partial void BtnLogin_TouchUpInside(UIButton sender)
    {
        if (txtPassword.Text != "" && txtUsername.Text != "")
        {
            //send UN & PD to webservice for validation.
            xxx.xxx.xxx.Services s = new xxx.xxx.xxx.Services();
            bool result = s.validateLogin(txtUsername.Text, txtPassword.Text);
            if (result)
            {
                try
                {
                    LocationViewController location = this.Storyboard.InstantiateViewController("LocationViewController") as LocationViewController;

                    if (location != null)
                        this.NavigationController.PushViewController(location, true);
                }
                catch (Exception ex)
                {
                    LoginFail("Error", ex.Message);
                }
            }
            else
            {
                LoginFail("Login", "Invalid username or password.");
            }
        }
        else
        {
            LoginFail("Login", "You must enter both your username and password.");
        }
    }

And my Storyboard

2 个答案:

答案 0 :(得分:3)

因为您的登录viewController不在NavigationController中,所以当您使用this.NavigationController时,它将抛出空引用异常。

要解决这个问题,有两种方法:

  • 将登录ViewVontroller放入NavigationController,使NavigationController(使用登录页面的rootviewController)成为故事板的初始控制器。

  • 更改此代码this.NavigationController.PushViewController(location, true);

    this.PresentViewController(location, true, null);

答案 1 :(得分:0)

您的屏幕需要包含在UINavigationController中。

如果您使用的是故事板,请在屏幕前放置一个UINavigationController,然后将一个segue从导航控制器拖到屏幕上。 segue设置为Root。

如果您使用的是代码:

new UINavigationController(new [your screen class]);