从UIApplication继承类中导航

时间:2017-10-24 15:05:31

标签: c# ios xamarin xamarin.ios

我已经思考了好几个小时了但是无济于事。我试图在我的iPad应用程序中添加一个方法,只要120秒没有活动,它就会将其发送回起始屏幕。

我对Xamarin和IOS编程都很陌生,所以如果我从完全错误的角度接近这个,那就道歉了。 我创建了一个类似于

的类
[Register("ElectronicReceptionMain")]
public class ElectronicReceptionMain : UIApplication
{       
    public override void SendEvent(UIEvent uievent)
    {
        Debug.WriteLine("SendEvent");            
        var allTouches = uievent.AllTouches;
        if(allTouches.Count > 0)
        {
            ResetIdleTimer();
        }            
        base.SendEvent(uievent);
    }

    NSTimer idleTimer;
    void ResetIdleTimer()
    {            
        idleTimer = NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(120), RefreshScreen);
    }

    void RefreshScreen(NSTimer obj)
    {
        Debug.WriteLine("Elapsed");                      
        UIStoryboard StoryBoard = UIStoryboard.FromName("Main", null);
        ViewController uvc = StoryBoard.InstantiateViewController("StartScreenController") as ViewController;
        SharedApplication.KeyWindow.RootViewController.NavigationController.PushViewController(uvc, true);

    }
}

此计时器工作正常,(调试消息打印出来但不会失败)。但是我无法使NavigationController成为null以外的任何东西,显然会导致null引用异常。

我也试过

uvc.NavigationController.PushViewController(uvc, true);

同样的问题。我的故事板中有一个导航控制器,从一个UIView到另一个UIView时屏幕之间有成功的导航。

我已经逐步完成了我的代码1行,它绝对是 null

的NaviagtionController

非常感谢任何帮助。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您的RootViewController应该是UINavigationViewcontroller。在你的AppDelgate中,你需要创建一个UINavigationViewController的实例并将它传递给它的InitialViewControllerInstance。并将UINavigationController的实例存储在一个变量(navController)中,如下所示:

<强> AppDelegate.cs

public UINavigationController navController;

    public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
    {
        //Here you need to instantiate your first ViewController instance from the storyboard and pass as an argument to the UINavigationController
        navController = new UINavigationController(yourInitialViewControllerInstance);
        Window = new UIWindow(UIScreen.MainScreen.Bounds);
        Window.RootViewController = navController;
        Window.MakeKeyAndVisible ();

        return true;
    }

然后,如果您要从任何其他类导航到任何其他View Controller,您只需从navController访问AppDelgate对象的实例,然后按以下方式导航:

void RefreshScreen(NSTimer obj)
{
      Debug.WriteLine("Elapsed");                      
      UIStoryboard StoryBoard = UIStoryboard.FromName("Main", null);
      ViewController uvc = StoryBoard.InstantiateViewController("StartScreenController") as ViewController;

     //Navigate using the navController Instance from the appDelgate
     ((AppDelegate)UIApplication.SharedApplication.Delegate).navController.PushViewController(uvc, true);
}