如何在 iOS 的 Xamarin Forms 中实现长按?

How to implement long press in Xamarin Forms for iOS?

我需要在 Xamarin Forms 中为 iOS 实现长按,但没有找到我需要的 post。我的工作代码如下。希望对大家有帮助。

我的自定义class ImgButton 继承自Grid。在其他情况下,您只需要按照 [table].[1]

将 ViewRenderer 替换为另一个渲染器

因为我只想在某些情况下启用长按,ImgButton 有一个 属性 EnableLongPress。

using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using UIKit;

[assembly: ExportRenderer (typeof(ImgButton), typeof(ImgButtonRenderer))]
namespace MyApp.iOS.Renderers
{
    public class ImgButtonRenderer : ViewRenderer<ImgButton,ImgButtonRenderer>
    {
        private UILongPressGestureRecognizer longPressGestureRecognizer;

    protected override void OnElementChanged ( ElementChangedEventArgs<ImgButton> e )
    {
        base.OnElementChanged ( e );

        if ( e.NewElement != null ) 
        {
            if ( ! e.NewElement.EnableLongPress )
                return;

            Action longPressAction = new Action ( () => 
            {
                if ( longPressGestureRecognizer.State != UIGestureRecognizerState.Began )
                    return;

                Console.WriteLine ( "Long press for " + e.NewElement.Text );

                // Handle the long press in the PCL
                e.NewElement.OnLongPress ( e.NewElement );
            });

            longPressGestureRecognizer = new UILongPressGestureRecognizer ( longPressAction );
            longPressGestureRecognizer.MinimumPressDuration = 0.5D;
            AddGestureRecognizer ( longPressGestureRecognizer );
        }

        if ( e.NewElement == null ) 
        {
            if ( longPressGestureRecognizer != null ) 
            {
                RemoveGestureRecognizer ( longPressGestureRecognizer );
            }
        }

        if ( e.OldElement == null ) 
        {
            if ( longPressGestureRecognizer != null )
                AddGestureRecognizer ( longPressGestureRecognizer );
        }
    }
}

在 ImgButton 中 class:

public void OnLongPress ( ImgButton button )
    // Here when a long press happens on an ImgButton
    {
        // Inform current page
        MessagingCenter.Send<ImgButton, ImgButton> ( this, "LongPressMessageType", button );
    }