首页 > 解决方案 > 在 Xamarin.iOS 中以编程方式关闭 UIAlertView

问题描述

我陷入了一个奇怪的场景,我需要通过获取实例以编程方式从另一个视图控制器中关闭活动的 UIAlertView。

实际上,我正在研究 AutoClose 功能(在 System.Timer 上工作),当 Timer 用完时,我需要执行一些操作(在 View Model 中执行)并关闭活动的 UIAlertView 或 UIViewController 窗口并导航到 HomeView。

我可以使用 UIViewController 但我找不到任何方法来关闭从另一个视图控制器呈现的 UIAlertView?

注意 - 我知道此 API 已被弃用,但使用 UIAlertController 会导致大量代码更改,我没有时间进行更改。

我正在使用下面的方法来完成,但是一旦 AlertView 被解雇,我就无法点击屏幕上的任何地方。

UIWindow window = UIApplication.SharedApplication.KeyWindow;
UIViewController rootViewController=window.RootViewController;

if(rootViewController.ModalViewController is UIAlertController)
{
    rootViewController.ModalViewController.DismissViewController(true,null);    
}

另外,我可以知道我们如何查看 Xamarin Studio 中的视图层次结构吗?

标签: xamarin.ios

解决方案


尝试使用以下代码:

UIAlertView alertView = new UIAlertView("Title", "Content",this,"OK");
alertView.Show();

UIActivityIndicatorView indicatorView = new UIActivityIndicatorView();
indicatorView.BackgroundColor = UIColor.Red;
indicatorView.Center = new CGPoint(alertView.Bounds.Size.Width / 2, 
alertView.Bounds.Size.Height - 40.0);
indicatorView.StartAnimating();
alertView.InsertSubview(indicatorView,0);

如果您想关闭 AlertView(例如以下代码中的示例,我会在 3 秒后关闭它):

NSTimer.CreateScheduledTimer(3, (t) =>
        {
            alertView.DismissWithClickedButtonIndex(0, true);
        });

推荐阅读