【问题标题】:How to implement long press in Xamarin Forms for iOS?如何在 Xamarin Forms for iOS 中实现长按?
【发布时间】:2019-08-26 19:49:42
【问题描述】:

我需要在 Xamarin Forms for iOS 中实现长按,但没有找到我需要的帖子。我的工作代码如下。希望它可以帮助某人。

【问题讨论】:

    标签: ios xamarin xamarin.forms long-press


    【解决方案1】:

    我的自定义类 ImgButton 继承自 Grid。在其他情况下,您只需要根据此 [table] 将 ViewRenderer 替换为另一个渲染器。[1]

    由于我希望仅在某些实例上启用长按,因此 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 类中:

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

    【讨论】:

    • 如果用户长时间按住按钮,系统错误可能导致消息订阅者的代码运行两次而不是一次。在该代码中,您需要添加如下内容:
    • if ( DateTime.Now - previousLongPressDateTime
    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 2021-11-05
    • 2017-09-20
    • 2016-12-03
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多