简体   繁体   中英

ViewCell ForceUpdateSize not working sometimes

I am using a custom ViewCell in Xamarin Forms which looks like this:

public class NativeCell : ViewCell
{
    public double Height
    {
        get
        {
            return base.Height;
        }
        set
        {
            base.Height = value;
            ForceUpdateSize();
        }
    }
}

I have also created a method to animate the colapse of the ViewCell which works as expected. However, with the overlay that comes with await, each loop iteration lasts up to 100ms instead of 1ms:

async public void Colapse()
{
    for (double i = Height; i >= 0; i--)
    {
        Height = i;
        await Task.Delay(1);
    }
}

So I made another method that used the Stopwatch to do the waiting:

async public void Colapse()
{
    var Timer = new Stopwatch();

    for (double i = Height; i >= 0; i--)
    {
        Height = i;

        Timer.Start();
        while(Timer.Elapsed.TotalMilliseconds < 1)
        {
        }
        Debug.WriteLine("-->" + Timer.Elapsed.TotalMilliseconds);
        Timer.Reset();
    }
} 

This last method reports that the wait time is now usually 1.1ms - 1.3ms. Which is great. However, the Height asignment is not doing anything. Or at least ForceUpdateSize is not triggering.

We need to solve few problems here.

  1. You have to specify HasUnevenRows in list view

  2. You cannot do "double i = Height" because Height will be "-1"

  3. You last function setting Height using StopWatch is not really async, so you UI will not be updated till function exits.

  4. Because Task.Delay is slow we can use Device timer with tick interval

Below is the solution that I tested on Android. The code is inside ViewCell in PCL

int currentHeight;
        public void Colapse()
        {
            currentHeight = (int)this.View.Height;
            Device.StartTimer(new TimeSpan(100), timerTick);
        }

        private bool timerTick()
        {
            if (currentHeight <= 0)
                return false;
            else
            {
                Height = currentHeight--;
                ForceUpdateSize();
                return true;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM