如何覆盖Xamarin.IOS UIButton的LayoutSublayersOfLayer行为?

时间:2016-08-01 15:03:40

标签: c# ios swift uibutton xamarin.ios

我移植到Xamarin.IOS是一个快速库,使用UIButton制作一些材质设计动画。

swift对应物是UIButton的子类,并覆盖layoutSublayersOfLayer。

夫特:

public override func layoutSublayersOfLayer(layer: CALayer) {
    super.layoutSublayersOfLayer(layer)
    if self.layer == layer {
        layoutShape()
        layoutVisualLayer()
    }
}

在Xamarin方面,我注意到这个方法是通过CALayerDelegate调用的,它通过de property Delegate与CALayer相关联。 我试图继承CALayerDelegate并替换de Delegate属性,但是当我这样做时,按钮没有正确呈现并停止响应事件。

有没有办法在Xamarin.Ios上覆盖layoutSublayersOfLayer?在绘制特定图层之前,是否有其他方法可以覆盖以准备内容?

public class MaterialButtonLayerDelegate : CALayerDelegate
{

    private readonly MaterialButton _button;

    public MaterialButtonLayerDelegate(MaterialButton button):base()
    {
        _button = button;
    }

    public override void LayoutSublayersOfLayer(CALayer layer)
    {
        if (_button.Layer == layer)
        {
            _button.LayoutShape();
            _button.LayoutVisualLayer();
        }
    }
}

[Register("MaterialButton")]
public class MaterialButton : UIButton
{
    public CAShapeLayer VisualLayer { get; private set; } = new CAShapeLayer();

    public MaterialButton(CGRect frame):base(frame)  
    {
        PrepareView();
    }

    protected void PrepareView()
    {
        Layer.Delegate = new MaterialButtonLayerDelegate(this);

        ContentScaleFactor = MaterialDevice.Scale();
        PrepareVisualLayer();
    }

    protected virtual void PrepareVisualLayer()
    {
        VisualLayer.ZPosition = 0;
        VisualLayer.MasksToBounds = true;
        Layer.AddSublayer(VisualLayer);
    }

    protected virtual void LayoutShape()
    {
        //...
    }

    protected virtual void LayoutVisualLayer()
    {
        //...
    }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

唯一可行的方法是扩展CALayerDelegate类并将其设置为CAShapeLayer委托。请务必尽可能调用委托人的基本成员,因为它在幕后执行必要的绑定。

public override void LayoutSublayersOfLayer(CALayer layer)
{
    base.LayoutSublayersOfLayer(layer);

    if (_button.Layer == layer)
    {
        _button.LayoutShape();
        _button.LayoutVisualLayer();
    }
}