ContentView(iOS)的自定义渲染器

时间:2017-01-24 15:45:13

标签: ios xamarin background xamarin.forms

我推迟了以下

public class ViewBase : ContentView
{
    //...
}

当我在XAML中使用它时

<local:ViewBase xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:local="clr-namespace:MyForms;"
    x:Class="MyForms.Finder" 
    BackgroundColor="Color.Yellow">

    <!-- ... -->

</local:ViewBase>

当我使用CustomRenderer时,甚至(如下所示)不执行任何操作,未设置上面的BackgroundColor。当我没有定义以下行时,背景为黄色,如预期的那样。

[assembly: ExportRenderer(typeof(ViewBase), typeof(ViewRendererBase))]
namespace MyiOS
{    
    public class ViewRendererBase : ViewRenderer
    {
    }
}

BackgroundColor是ViewRenderer的一个属性。我看了一下代码,看来Control是没有设置的(我不调用SetNativeControl)它不能将Control.BackgroundColor设置为一个值。但为什么会这样呢?我的猜测是ViewRenderer的继承有问题,因为默认行为在ContentView上使用了不同的东西!?

1 个答案:

答案 0 :(得分:4)

不确定这是我们的文档[1]中的错误还是ViewRenderer方法的iOS SetBackgroundColor代码[2]中的错误。所以有几种方法可以解决这个问题。一种是让您的自定义渲染器继承自VisualElementRenderer<T>,例如:

public class ViewBaseRenderer : VisualElementRenderer<ContentView>
{
    //...
}

使用以下命令检查iOS代码中的默认渲染器类型时:

var contentRenderer = Platform.CreateRenderer(new ContentView())
var rendererType = contentRenderer.GetType();

rendererTypeVisualElementRenderer<T>,因此这似乎是Forms使用的默认渲染器,因此它似乎是文档中的错误。

另一个&#34;解决方法&#34;将使用ViewRenderer但覆盖SetBackgroundColor方法:

public class ViewBaseRenderer : ViewRenderer
{
    protected override void SetBackgroundColor(Color color)
    {
        base.SetBackgroundColor(color);

        if (NativeView == null)
            return;

        if (color != Color.Default)
            NativeView.BackgroundColor = color.ToUIColor();
    }

我已经与Xamarin Forms团队讨论了这个问题,以确定它是文档中的错误还是ViewRenderer的Forms iOS平台代码中的错误。如果你查看我链接的表单源代码[2],你会看到如果Control为null,在这种情况下,它将永远不会设置背景颜色。通过覆盖并添加代码来设置NativeView的背景颜色,您可以解决这个可能的错误。

显然,似乎文档出错了。如果您使用ViewRenderer,则必须自己设置Control。继承自ViewRenderer的其他呈现器(如LabelRender)已设置Control,但ViewRenderer未设置,因此您必须在SetNativeControl()中调用OnElementChanged {1}}覆盖以创建和设置本机控件。看到这篇论坛帖子[3]。就个人而言,我认为应该从默认使用的渲染器继承,在这种情况下是VisualElementRenderer<T>

[1] https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/renderers/#Layouts

[2] https://github.com/xamarin/Xamarin.Forms/blob/74cb5c4a97dcb123eb471f6b1dffa1267d0305aa/Xamarin.Forms.Platform.iOS/ViewRenderer.cs#L99

[3] https://forums.xamarin.com/discussion/comment/180839#Comment_180839