如何分配 UIPopoverPresentationControllerDelegate

How to assign the UIPopoverPresentationControllerDelegate

我尝试使用UIPopoverPresentationController。对于演示,我需要分配委托 (UIPopoverPresentationControllerDelegate) 才能使用 prepareForPopoverPresentation popoverPresentationControllerDidDismissPopover 等方法。

如果将视图控制器分配给委托 属性 我得到

Error CS0266 Cannot implicitly convert type 'UIKit.UIViewController' to 'UIKit.IUIPopoverPresentationControllerDelegate'. An explicit conversion exists (are you missing a cast?)

那么我的选择是什么?在原生世界中,可以添加所需的协议,但你不能在 Xamarin 中这样做。我希望弹出窗口中显示的视图控制器收到通知(准备、关闭、...)。我该怎么做?

当然我可以创建一个 UIPopoverPresentationControllerDelegate 的新实例并分配它,但是我会以某种方式(例如通过事件)将委托与视图控制器连接起来。有更简单的解决方案吗?

编辑

看起来 Xamarin 没有公开 WeakDelegate 属性 并且还使委托 class 成为协议而非接口的抽象 class。在这种情况下 - 您将必须创建另一个实现 UIPopoverPresentationControllerDelegate 的 class 和另一个实现 UIPopoverControllerDelegate 的 class。

在未来,值得注意的是通常有一个 WeakDelegate 属性(连同 Delegate)允许将任何 class 分配给委托并实现协议通过 ExportAttribute 隐式地在协议方法上。 Xamarin 有时也会使用协议的匹配接口(例如IUIPopoverPresentationControllerDelegate)而不是匹配抽象class(UIPopoverPresentationControllerDelegateclass)。


原答案大部分不正确

您的 UIViewController class 应该可以实现 IUIPopoverControllerDelegate 并实现您需要的任何方法。通常 iOS 协议会转换为 Xamarin.iOS 的接口,您可以通过在协议名称后附加 "I" 来找到它。

public class TestVC : UIViewController, IUIPopoverControllerDelegate
{
    public override UIPopoverPresentationController PopoverPresentationController {
        get {
            return base.PopoverPresentationController;
        }
    }

    [Export ("popoverControllerDidDismissPopover:")]
    public void DidDismiss (UIPopoverController popoverController)
    {
        throw new NotImplementedException ();
    }
}

这是我实现了一些弹出方法的示例。我希望这有帮助。我没有明确测试过这个,但我认为它应该有效。如果没有,请告诉我。

我的解决方案如下:

我将 UIPopoverPresentationControllerDelegate 子类化,在这里我定义了事件 PrepareForPopoverDidDismiss。所以我覆盖了 PrepareForPopoverPresentationDidDismissPopover 并抛出了所属事件。

然后我将此委托分配给我的 UIPopoverPresentationController 实例。通过订阅我的自定义委托的事件,我能够在弹出窗口显示和关闭时收到通知。无法进行转换(正如我在问题中尝试的那样)。

有了这个可以设置一些变量或从视图控制器调用一些方法,它显示在弹出窗口中。