【问题标题】:Xamarin iOS PushViewController null reference exceptionXamarin iOS PushViewController 空引用异常
【发布时间】:2017-07-19 21:56:49
【问题描述】:

我是 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

【问题讨论】:

  • 如果您的页面未包含在 UINavigationController 中,则 NavigationController 属性将为 null

标签: ios xamarin xamarin.ios uinavigationcontroller nullreferenceexception


【解决方案1】:

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

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

  • 将登录ViewVontroller放入NavigationController中,使NavigationController(带有登录页面的rootviewController)成为storyboard的初始Controller。

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

    this.PresentViewController(location, true, null);

【讨论】:

    【解决方案2】:

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

    如果您使用情节提要,请在屏幕前放置一个 UINavigationController 并将一个 segue 从导航控制器拖到您的屏幕上。 segue 设置为 Root。

    如果您使用的是代码:

    new UINavigationController(new [your screen class]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      相关资源
      最近更新 更多