0

我正在尝试学习如何创建自定义 NSCollectionViewLayout。我遵循了一些教程,但我总是得到相同的结果,一个空的 CollectionView。

我一直在使用的代码是这个:https ://github.com/Jatapiaro/CustomCollectionViewLayout

我对自定义 NSCollectionViewLayout 的实现是:

#import "CollectionViewCustomLayout.h"

@implementation CollectionViewCustomLayout {
    CGFloat _itemHeight;
}

- (instancetype)init
{
    if (self = [super init]) {
        _itemHeight = 100;
    }

    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
}

/**
 * The width and height of the entire collection view content
 */
- (NSSize)collectionViewContentSize
{
    NSInteger numberOfItems = self.collectionView.numberOfSections;

    if (!numberOfItems)
        return NSZeroSize;

    NSSize size = self.collectionView.superview.bounds.size;
    size.height = _itemHeight * numberOfItems;

    return size;
}

/**
 * Set the layout of each item inside the collection view
 */
- (NSArray<__kindof NSCollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(NSRect)rect
{
    NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:0];
    NSMutableArray<NSCollectionViewLayoutAttributes *> *attributes = [NSMutableArray array];

    for (NSInteger i = 0; i < numberOfItems; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        NSCollectionViewLayoutAttributes *itemAttributes = [NSCollectionViewLayoutAttributes layoutAttributesForItemWithIndexPath:indexPath];

        if (itemAttributes)
            [attributes addObject:itemAttributes];
    }

    return attributes;
}

- (NSCollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:0];

    if (!numberOfItems)
        return nil;

    NSRect frame = NSMakeRect(0, _itemHeight * indexPath.item, self.collectionViewContentSize.width, _itemHeight);

    NSCollectionViewLayoutAttributes *itemAttributes = [NSCollectionViewLayoutAttributes layoutAttributesForItemWithIndexPath:indexPath];
    itemAttributes.frame = frame;

    return itemAttributes;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(NSRect)newBounds
{
    return YES;
}

@end

即使调用了实现中的所有方法,一旦应用程序运行,我总是会得到以下结果。

CollectionView 失败

有谁知道我做错了什么?

4

0 回答 0