【发布时间】:2019-12-23 02:50:27
【问题描述】:
我在 Xamarin.Forms 项目中使用依赖服务,我想在 iOS 中显示一条 3 秒后自动消失的 toast 消息。是一个在iOS端使用的alert,消息可以显示,但不会消失,导致app死机。
我尝试禁用动画,但没有帮助。我在 iOS 项目中有以下代码。
[assembly: Xamarin.Forms.Dependency(typeof(MessageIOS))]
namespace DrawRegions.iOS.Services
{
public class MessageIOS : IMessage
{
const double LONG_DELAY = 3.5;
const double SHORT_DELAY = 2.0;
NSTimer alertDelay;
UIAlertController alert;
public void LongAlert(string message)
{
ShowAlert(message, LONG_DELAY);
}
public void ShortAlert(string message)
{
ShowAlert(message, SHORT_DELAY);
}
void ShowAlert(string message, double seconds)
{
alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
{
dismissMessage();
});
alert = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
}
void dismissMessage()
{
if (alert != null)
{
alert.DismissViewController(true, null);
}
if (alertDelay != null)
{
alertDelay.Dispose();
}
}
}
}
如果我拨打DependencyService.Get<IMessage>().ShortAlert("alert message"),消息会出现,但会一直停留,并且应用程序卡住了。
我已经在 iPhone 6 设备和 iPhone 6s 模拟器上进行了测试,操作系统版本均为 12.4。
对于Android端,toast会显示和其他任务同时运行,toast会自动消失。当然,Android 代码是无关紧要的。 如果我能得到一些帮助,非常感谢。
编辑: 我根据 StackOverFlow 线程做了一些改动如下,
{
const double LONG_DELAY = 3.5;
const double SHORT_DELAY = 0.75;
public void LongAlert(string message)
{
ShowAlert(message, LONG_DELAY);
}
public void ShortAlert(string message)
{
ShowAlert(message, SHORT_DELAY);
}
void ShowAlert(string message, double seconds)
{
var alert = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);
var alertDelay = NSTimer.CreateScheduledTimer(seconds, obj =>
{
DismissMessage(alert, obj);
});
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
}
void DismissMessage(UIAlertController alert, NSTimer alertDelay)
{
if (alert != null)
{
alert.DismissViewController(true, null);
}
if (alertDelay != null)
{
alertDelay.Dispose();
}
}
}
现在,toast 会自动消失,但是一旦显示了 toast,所有其他后台任务将不会被执行,例如我在显示 toast 时导航页面,但是,该页面不会被导航。但是如果我删除所有显示这些 toast 的代码,所有其他代码都将被执行。 但在 Android 上,所有代码都在显示和关闭 toast 时执行。
【问题讨论】:
-
你试过我的解决方案了吗?
标签: ios objective-c xamarin xamarin.forms xamarin.ios