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; } } }
