问题描述
我正在尝试学习如何创建自定义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
即使调用了实现中的所有方法,一旦应用运行,我总是会得到以下结果。
有人知道我在做什么错吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)