我想以编程方式点按"关闭"我的xamarin iOS应用中的错误提示按钮。为此,我需要在警报上执行与该按钮关联的操作。我在obj-c中看到this post如何做到这一点,但我无法弄清楚如何在Xamarin C#中做到这一点。我试过这样做:
Action closeButtonAction = Marshal.GetDelegateForFunctionPointer<Action>(AlertController.Alert.Actions[0].Handle);
closeButtonAction();
但是Actions Target属性为null,所以在尝试执行它时我得到了一个NRE。
答案 0 :(得分:1)
您可以通过UIAlertView
以编程方式解除DismissWithClickedButtonIndex
,然后通过Delegate.Clicked
致电代表。
IUIAlertViewDelegate
:public class UIAlertViewDelegate : NSObject, IUIAlertViewDelegate
{
[Export("alertViewCancel:")]
public void Canceled(UIAlertView alertView)
{
Console.WriteLine("IUIAlertViewDelegate Cancelled");
}
[Export("alertView:clickedButtonAtIndex:")]
public void Clicked(UIAlertView alertview, nint buttonIndex)
{
Console.WriteLine($"IUIAlertViewDelegate Clicked {buttonIndex}");
}
}
var autoCancelSeconds = 5;
var alert = new UIAlertView("StackOverflow", $"Auto cancel in {autoCancelSeconds} seconds", null, null, new[] { "Stack", "Over", "Flow" })
{
Delegate = new UIAlertViewDelegate()
};
alert.Show();
await Task.Run(async () =>
{
for (int i = autoCancelSeconds - 1; i >= 0; i--)
{
await Task.Delay(1000);
InvokeOnMainThread(() =>
{
alert.Message = string.Format($"Auto cancel in {i} seconds");
});
}
InvokeOnMainThread(() =>
{
alert.DismissWithClickedButtonIndex(1, true);
alert.Delegate.Clicked(alert, 1);
});
});
注意:不推荐使用UIAlertView
,您应该转到使用UIAlertController