UICollectionView 初始延迟与 PagingEnabled = true

UICollectionView initial lag with PagingEnabled = true

有我的情况:

问题是:

=> 预期:我不希望它在那一刻显示空白页。

这是我的代码:

public class CarouselWebTouch
    : UIView,
    IUICollectionViewSource,
    IUICollectionViewDelegateFlowLayout,
    ICarouselWebTouch
{
    const string DAY_CELL_ID = "webCellId";

    IList<PageItem> Pages = new List<PageItem>();
    UICollectionView CollectionView;
    Dictionary<int, CarouselWebCell> CacheWebCell = new Dictionary<int, CarouselWebCell>();

    ...

    public CarouselWebTouch()
    {
        var layout = new UICollectionViewFlowLayout();
        layout.MinimumLineSpacing = 0;
        layout.MinimumInteritemSpacing = 0;
        layout.ScrollDirection = UICollectionViewScrollDirection.Horizontal;
        layout.SectionInset = UIEdgeInsets.Zero;
        layout.HeaderReferenceSize = CGSize.Empty;
        layout.FooterReferenceSize = CGSize.Empty;

        CollectionView = new UICollectionView(CGRect.Empty, layout);
        CollectionView.AllowsSelection = true;
        CollectionView.BackgroundColor = UIColor.Clear;
        CollectionView.PagingEnabled = true;
        CollectionView.Delegate = this;
        CollectionView.DataSource = this;
        CollectionView.ShowsHorizontalScrollIndicator = false;
        CollectionView.RegisterClassForCell(typeof(CarouselWebCell), DAY_CELL_ID);
        Add(CollectionView);
    }

    public UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
    {
        var reusableCell = (CarouselWebCell)collectionView.DequeueReusableCell(DAY_CELL_ID, indexPath);
        return reusableCell;
    }
}

函数 GetCell 在第 0 节的第一次初始加载中调用。我想生成它的上一个和下一个单元格。 (也是第 1 节的意思)。

有什么方法可以强制它在初始加载短语中生成单元格数量?

UICollectionViewDataSourcePrefetching

A protocol that provides advance warning of the data requirements for a collection view, allowing the triggering of asynchronous data load operations.

您可以在现有的基于 NSObject 的 class 上实现 IUICollectionViewDataSourcePrefetching 接口(我在我的集​​合视图数据源上实现)并将其分配给 PrefetchDataSource 属性:

CollectionView.PrefetchDataSource = this;
CollectionView.PrefetchingEnabled = true; 

注意:如果您正在设置 PrefetchDataSource,则不需要将 PrefetchingEnabled 设置为 true,但您可以切换它 on/off 它需要暂时关闭预取一个原因。

您有一种必需方法 (PrefetchItems) 和一种可选方法 (CancelPrefetching),我强烈建议 您阅读 Apple 文档 让您了解这些方法何时被调用(它们不一定被每个单元格调用)

public void PrefetchItems(UICollectionView collectionView, NSIndexPath[] indexPaths)
{
    foreach (var prefetch in indexPaths)
    {
        Console.WriteLine($"PreFetch {prefetch.LongRow}");
    }
}

[Export("collectionView:cancelPrefetchingForItemsAtIndexPaths:")]
public void CancelPrefetching(UICollectionView collectionView, NSIndexPath[] indexPaths)
{
    foreach (var prefetch in indexPaths)
    {
        Console.WriteLine($"Cancel PreFetch {prefetch.LongRow}");
    }
}

注意:由于 CancelPrefetching 在 Xamarin/C# 接口中是可选的,因此您需要 Export 否则 UICollectionView 将看不到它已实现并且不叫它。

Apple 文档:UICollectionViewDataSourcePrefetching