Xamarin.Forms Button長按事件


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM