Xamarin FOrms iOS:ImageRenderer CreateNativeControl 错误

Xamarin FOrms iOS: ImageRenderer CreateNativeControl error

我正在尝试在 iOS 子 class 原生 UIImageView 中实现自定义 ImageRenderer,但我在使用 CreateNativeControl 时遇到了一些问题。

在较旧的 Xamarin.Forms 版本(如 4.2)中,我用 protected override UIImageView CreateNativeControl() { return new NativeImage(); } 初始化的自定义本机 class 看起来从未被调用(我在构造函数中登录的消息是未显示)。自定义渲染器已正确初始化(记录了正确的消息)。

在最新的稳定版(如4.4)中覆盖CreateNativeControl的return类型据说必须是FormsUIImageView,没听说过,反正我也试过subclass 但是和以前一样的问题,似乎它永远不会被调用,因为没有记录构造函数消息。自定义渲染器已正确初始化(记录了正确的消息)。

这里是我使用的代码:

public class IOSImageView : ImageRenderer
{
   public IOSImageView()
   {
   }

    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);

        if(Control == null)
        {
            return;
        }

        Console.WriteLine("PIPPO created from Custom Renderer");  //this message is correctly logged
    }


    protected override UIImageView CreateNativeControl()  //FormsUIImageView  in XF 4.4
    {
        return new NativeImage();
    }

}

public class NativeImage : UIImageView  //FormsUIImageView in XF 4.4
{
    public NativeImage() : base()
    {
        Console.WriteLine("PIPPO created from native IOS");  //this message is NOT logged
    }

    public override void TouchesBegan(NSSet touches, UIEvent evt)
    {
        base.TouchesBegan(touches, evt);
        Console.WriteLine("PIPPO touched");  //this (of course because no NativeImage is shown and there is no image to touch) is NOT logged
    }
}

FormsUIImageView 是 XF 4.4 之后新增的,你可以查看 Xamarin.Forms release notes

在你的情况下,你似乎想将 Image Renderer 设置为你的自定义 ImageView,对吧?

你应该调用 SetNativeControl()

protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
{
   base.OnElementChanged(e);
   if(Control!=null)
   {
      SetNativeControl(new NativeImage());
   }
}

public class NativeImage : FormsUIImageView 
{
    public NativeImage() : base()
    {
         this.UserInteractionEnabled = true;
    }

    public override void TouchesBegan(NSSet touches, UIEvent evt)
    {
        base.TouchesBegan(touches, evt);
        Console.WriteLine("PIPPO touched");  //this (of course because no NativeImage is shown and there is no image to touch) is NOT logged
    }
}