Как реализовать долгое нажатие в Xamarin Forms для iOS?

В Java все переменные, которые вы объявляете, на самом деле являются «ссылками» на объекты (или примитивы), а не самими объектами.

При попытке выполнить один метод объекта , ссылка просит живой объект выполнить этот метод. Но если ссылка ссылается на NULL (ничего, нуль, void, nada), то нет способа, которым метод будет выполнен. Тогда runtime сообщит вам об этом, выбросив исключение NullPointerException.

Ваша ссылка «указывает» на нуль, таким образом, «Null -> Pointer».

Объект живет в памяти виртуальной машины пространство и единственный способ доступа к нему - использовать ссылки this. Возьмем этот пример:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

И в другом месте вашего кода:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

Это важно знать - когда больше нет ссылок на объект (в пример выше, когда reference и otherReference оба указывают на null), тогда объект «недоступен». Мы не можем работать с ним, поэтому этот объект готов к сбору мусора, и в какой-то момент VM освободит память, используемую этим объектом, и выделит другую.

0
задан BillF 4 April 2019 в 23:40
поделиться

1 ответ

Мой пользовательский класс ImgButton наследуется от Grid. В других случаях вам просто нужно заменить 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 );
    }
0
ответ дан BillF 4 April 2019 в 23:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: