Search code examples
iosxamarinxamarin.formslong-press

How to implement long press in Xamarin Forms for iOS?


I needed to implement long press in Xamarin Forms for iOS and did not find the post I needed. My working code is below. Hope it helps someone.


Solution

  • My custom class ImgButton inherits from Grid. In other cases you would just need to replace ViewRenderer with another renderer as per this [table].[1]

    As I want long press to be enabled only on certain instances, ImgButton has a property 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 );
            }
        }
    }
    

    And in the 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 );
        }