I am working in xamarin.forms
project and I am stuck at a problem.
I want the main screen to remain enabled whenever UIAlertController
(in android terms Toast
) is shown. Here for me both the things are important.
When showing the alert, buttons from the background view should be clickable. And because an important message needs to be shown, the alert should also appear in parallel for given time.
In android, Toast
does not interfere with the user interaction on main screen. Can I have same working thing in iOS ?
Here is what I have tried in my dependency service.
void ShowAlert(string message, double seconds)
{
try
{
if (alert == null && alertDelay == null)
{
alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
{
Device.BeginInvokeOnMainThread(() =>
{
DismissMessage();
});
});
Device.BeginInvokeOnMainThread(() =>
{
try
{
alert = UIAlertController.Create("", message, UIAlertControllerStyle.Alert);
alert.View.UserInteractionEnabled = true;
topViewControllerWithRootViewController(UIApplication.SharedApplication.KeyWindow.RootViewController).PresentViewController(alert, true, () =>
{
UITapGestureRecognizer tap = new UITapGestureRecognizer(() => { }); // I have tried this but nothing happens
alert.View.Superview.Subviews[0].AddGestureRecognizer(tap);
});
}
catch (Exception ex)
{
var Error = ex.Message;
}
});
}
}
catch (Exception ex)
{
var Error = ex.Message;
}
}
void DismissMessage()
{
if (alert != null)
{
alert.DismissViewController(true, null);
alert = null;
}
if (alertDelay != null)
{
alertDelay.Dispose();
alertDelay = null;
}
}
UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
{
try
{
if (rootViewController is UITabBarController)
{
UITabBarController tabBarController = (UITabBarController)rootViewController;
return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
}
else if (rootViewController is UINavigationController)
{
UINavigationController navigationController = (UINavigationController)rootViewController;
return topViewControllerWithRootViewController(navigationController.VisibleViewController);
}
else if (rootViewController.PresentedViewController != null)
{
UIViewController presentedViewController = rootViewController.PresentedViewController;
return topViewControllerWithRootViewController(presentedViewController);
}
}
catch (Exception)
{
}
return rootViewController;
}