类型为Custom的UIButton丢失Click事件

时间:2016-09-08 16:40:54

标签: ios uibutton xamarin.ios xamarin.forms

我有以下代码在Xamarin中创建自定义iOS UIButton:

    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        // will have to create a native Custom type of ios button to avoid text dimming
        // when touched

        // logic of element processing from
        // https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/view/

        // except we don't call the base immediately
        // because it will create the Control for us, but we don't want that here
        if (Control == null)
        {
            // instantiate the native control and assign it to the Control property with
            // the SetNativeControl method
            uiBtn = new UIButton(UIButtonType.Custom);
            SetNativeControl(uiBtn); // should set Control to the newly created element 
            // and prevent base.OnElementChanged(e) from creating a new element instead
        }

        base.OnElementChanged(e);

        // some button customization code here - it does not matter, the issue happens also without it...

渲染器代码工作正常,但现在我的Xamarin.Forms按钮上没有收到任何Clicked事件。

如何恢复丢失的点击功能?

1 个答案:

答案 0 :(得分:1)

最后在Xamarin源代码中我发现了这个:

https://github.com/xamarin/Xamarin.Forms/blob/2d9288eee6e6f197364a64308183725e7bd561f9/Xamarin.Forms.Platform.iOS/Renderers/ButtonRenderer.cs

看看OnElementChanged,我有点惊讶的是,只有当这个OnElementChanged实例创建本机元素时才附加事件。不确定,为什么这样做,但至少现在我知道如果我自己创建一个控件,那么我也必须自己连接点击事件。