在旋转电话不起作用时更改CollectionView的范围

问题描述 投票:0回答:1

我正在尝试旋转iPhone时更改CollectionView的跨度。为了简单起见,只需在纵向显示2列,在横向显示4列即可。当从纵向模式旋转到横向模式时,它可以工作,但是当旋转回到纵向模式时,它始终显示1列。我的代码喜欢,

    VideoCollectionView = new CollectionView()
        {
            ItemsLayout = new GridItemsLayout(2, ItemsLayoutOrientation.Vertical),
        };
    ...

    private static double screen_width = 1280.0;
    private static double screen_height = 720.0;

    protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);

        if ((Math.Abs(screen_width - width) > minimum_double) || (Math.Abs(screen_height - height) > minimum_double))
        {
            screen_width = width;
            screen_height = height;

            int split;
            if (screen_width > screen_height)
            {   // landscape mode
                split = 4;
            }
            else
            {   // portrait mode
                split = 2;
            }

            VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
        }
    }

这是一个错误吗?还是我应该使用其他方式?感谢您的帮助。

c# xamarin.forms multiple-columns grid-layout collectionview
1个回答
0
投票

您可以使用Singleton来存储当前方向。因为将屏幕尺寸设置为s静态值是不明智的。可能会在不同尺寸的设备上引起问题。

public class CurrentDevice
{
    protected static CurrentDevice Instance;
    double width;
    double height;

    static CurrentDevice()
    {
        Instance = new CurrentDevice();
    }
    protected CurrentDevice()
    {
    }

    public static bool IsOrientationPortrait()
    {
        return Instance.height > Instance.width;
    }

    public static void SetSize(double width, double height)
    {
        Instance.width = width;
        Instance.height = height;
    }
}

并且在方法中

protected override void OnSizeAllocated(double width, double height)
{
   base.OnSizeAllocated(width, height);


   if (CurrentDevice.IsOrientationPortrait() && width > height || !CurrentDevice.IsOrientationPortrait() && width < height)
   {
      int split;
      CurrentDevice.SetSize(width, height);

      // Orientation got changed! Do your changes here
      if (CurrentDevice.IsOrientationPortrait())
      {
         // portrait mode
         split = 2;
      }

      else
      {
         // landscape mode
         split = 4;
      }

      VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
   }


}
© www.soinside.com 2019 - 2024. All rights reserved.