获取iOS .NET MAUI中当前的ViewController

问题描述 投票:0回答:1

我正在将必须的 Xamarin Forms 代码移植到 .NET MAUI,但是用于获取当前视图控制器的代码不起作用,如何在 MAUI 中获取当前 ViewControler

相关代码在这里:在Xamarin表单中使用UIDocumentPickerViewController作为依赖服务

相关Xamarin Forms(iOS)代码:

public UIViewController GetCurrentUIController()
{
    UIViewController viewController;
    var window = UIApplication.SharedApplication.KeyWindow;
    if (window == null)
    {
        return null;
    }

    if (window.RootViewController.PresentedViewController == null)
    {
        window = UIApplication.SharedApplication.Windows
                 .First(i => i.RootViewController != null &&
                             i.RootViewController.GetType().FullName
                             .Contains(typeof(Xamarin.Forms.Platform.iOS.Platform).FullName));
    }

    viewController = window.RootViewController;

    while (viewController.PresentedViewController != null)
    {
        viewController = viewController.PresentedViewController;
    }

    return viewController;
}
c# .net xamarin xamarin.ios maui
1个回答
0
投票

在花费了大量时间移植此代码后,我意识到 Xamarin Forms 中可用的相关命名空间现在要么是内部的,要么不再存在,因此我花了一些时间搜索使用 MAUI 执行此操作的正确方法是什么我再次没有找到,但是经过一番探查这个 Microsoft 文档我意识到 ApplicationModel 的 Platform 类正是我所需要的,

var currentViewController = Microsoft.Maui.ApplicationModel.Platform.GetCurrentUIViewController();

在这里添加这个,这样其他人就不会在这个简单的事情上浪费一两个小时:)

© www.soinside.com 2019 - 2024. All rights reserved.