隐藏

Xamarin.Forms Button长按事件

发布:2021/10/25 10:32:21作者:管理员 来源:本站 浏览次数:1088

在平时的开发中,我们经常遇到需要Button能够拥有长按事件,但是在Xamarin.Forms中Button并没有该事件,

此时我们如何来实现呢?

我们知道在Xamarin.Forms中可以通过CustomRenderer来根据不同平台各自处理。

这里我们即便用这个方法来实现长按事件:

Android的长按事件:

复制代码
[assembly: Xamarin.Forms.ExportRenderer (typeof (MyButton), typeof (MyButtonRenderer))] namespace MyApp.Android
{ public class MyButtonRenderer : ButtonRenderer
    { protected override void OnElementChanged (ElementChangedEventArgs<global::Xamarin.Forms.Button> e)
                { base.OnElementChanged (e); if (e.OldElement == null) { var nativeButton = Control;
                        nativeButton.LongClick += delegate { //Do something  };
                    }
                }
    }
}
复制代码

iOS长按事件处理:

复制代码
[assembly:ExportRenderer (typeof(ButtonWithLongPressGesture), typeof(LongPressGestureRecognizerButtonRenderer))] namespace SampleApp.iOS
{ public class LongPressGestureRecognizerButtonRenderer : ButtonRenderer
    {
        ButtonWithLongPressGesture view; public ButtonPressGestureRecognizerImageRenderer ()
        { this.AddGestureRecognizer (new UILongPressGestureRecognizer ((longPress) => { if (longPress.State == UIGestureRecognizerState.Began) {
                    view.HandleLongPress(view, new EventArgs());
                }
            }));
        } protected override void OnElementChanged (ElementChangedEventArgs<Button> e)
        { base.OnElementChanged (e); if (e.NewElement != null)
                view = e.NewElement as ButtonWithLongPressGesture;
        }
    }
}
复制代码