Xamarin.Forms Button长按事件
在平时的开发中,我们经常遇到需要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; } } }