#cocoa #nscollectionview #nscollectionviewlayout
#cocoa #nscollectionview #nscollectionviewlayout
Вопрос:
Я пытаюсь узнать, как создать пользовательский 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
Даже если вызываются все методы в реализации, я всегда получаю следующий результат после запуска приложения.
У кого-нибудь есть представление о том, что я делаю неправильно?
Комментарии:
1. Вы проверили возвращаемые значения?
2. Да, я это сделал. Все они возвращают ненулевое значение
3. Все ли фреймы в порядке?
4. Нет, их высота неверна. Мое переопределение метода init не вызывается. И высота никогда не устанавливается равной 100. Я не знаю, почему метод init не вызывается.
5. Код, который вы вызываете
init
, не выполняется. Макет загружается из кончика иinitWithCoder:
вызывается.