![](/img/trans.png)
[英]Display an Alert popup when application is receiving an Apple Push Notification in iOS
[英]In .NET Maui for iOS, can you display an alert from a community Popup?
我有一个社区工具包弹出窗口 (toolkit:Popup),它会在按下按钮时询问问题。
<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class="PinPopUp">
<VerticalStackLayout>
<Button x:Name="btnRate" Text="Rate" FontSize="12" Clicked="btnRate_Clicked"
VerticalOptions="Center" HeightRequest="40" HorizontalOptions="Fill" Padding="8" />
</VerticalStackLayout>
</toolkit:Popup>
后面有这段代码:
private async void btnRate_Clicked(object sender, EventArgs e)
{
try
{
bool answer = await App.Current.MainPage.DisplayAlert("Rating", message, "Yes", "No");
if (answer)
{
await App.Current.MainPage.DisplayAlert("Submitting...", result, "OK");
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
await App.Current.MainPage.DisplayAlert("Oops!", "There was an error rating this shop! =(", "OK");
}
}
这在 Android 上工作正常,但在 iOS 上,一旦它到达显示第一个警报的行,代码执行就返回到表单,没有任何显示。 您可以重复单击该按钮。
如果重要,则 Popup 由 ContentView 而不是 ContentPage 调用。
我觉得警报出现在屏幕上看不到的某个地方,也许在某些东西后面。 有没有办法确保它在所有内容之前?
您可以编写平台代码来实现它。 我做了一个小演示。 你可以试试
在项目文件夹中,创建一个新的部分class,我们称之为 DisplayAlertService:
namespace CommunityPopup75242427
{
public partial class DisplayAlertService
{
public partial void DisplayAlert();
}
}
然后在Platforms/iOS文件夹中创建另一个部分 class,也将其命名为 DisplayAlertService。 注意命名空间要和上面的文件一样:
namespace CommunityPopup75242427
{
public partial class DisplayAlertService
{
public partial void DisplayAlert()
{
var okCancelAlertController = UIAlertController.Create("Alert Title", "Choose from two buttons", UIAlertControllerStyle.Alert);
//Add Actions
okCancelAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, alert => Console.WriteLine("Okay was clicked")));
okCancelAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alert => Console.WriteLine("Cancel was clicked")));
UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow();window.RootViewController.PresentedViewController.PresentViewController(okCancelAlertController, true, null);
}
}
}
然后在弹出窗口中,您可以使用单击的按钮调用它,例如:
async void mybutton_Clicked(System.Object sender, System.EventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
var d = new DisplayAlertService();
d.DisplayAlert();
});
}
更多信息,您可以参考:
1. How To Write Platform-Specific Code in .NET MAUI and MauiPlatformCodeSample 代码。
希望对你有效。
您上面的 DisplayAlert 调用确实适用于 Android 和 iOS; 唯一可能妨碍您捕获响应的可能是 iOS 确实需要它在主 ui 线程上运行。 也许尝试将您的异步代码包含在其中:
MainThread.BeginInvokeOnMainThread(() =>
{
bool answer = await App.Current.MainPage.DisplayAlert("Rating", message, "Yes", "No");
if (answer)
{
await App.Current.MainPage.DisplayAlert("Submitting...", result, "OK");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.