Я пытаюсь настроить позиции заголовков в UICollectionView
, используя подкласс UICollectionViewFlowLayout
(на основе кода для сложенных заголовков, который показан введите здесь описание ссылки).
В качестве минимального теста предположим, что я просто хочу добавить фиксированное смещение к положению всех заголовков:
- Я добавляю все заголовки в массив, возвращаемый
layoutAttributesForElementsInRect
, чтобы все всегда обрабатывались (может быть, это причина проблемы, я не уверен) - Затем я обновляю каждый заголовок, добавляя фиксированное смещение в
layoutAttributesForSupplementaryViewOfKind
Полная реализация включена в конце этого поста.
(Кстати, я знаю, что добавление всех заголовков, в том числе за пределами прямоугольника, строго говоря, не обязательно на первом шаге, но это упрощенный пример более сложной настройки в позиции, которую я хочу сделать, что приведет к тому, что все заголовки для отображения в прямоугольнике рисования.)
Однако, когда я запускаю код, я получаю следующее NSInternalInconsistencyException
:
2014-01-15 00:41:50.130 CollectionStackedHeaders[60777:70b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'layout attributes for supplementary item at index path (<NSIndexPath: 0x8a7db90> {length = 2, path = 0 - 0})
changed from <UICollectionViewLayoutAttributes: 0x8a7f8b0> index path: (<NSIndexPath: 0x8a7d9c0> {length = 2, path = 0 - 0}); element kind: (UICollectionElementKindSectionHeader); frame = (0 0; 320 50);
to <UICollectionViewLayoutAttributes: 0x8a7fb80> index path: (<NSIndexPath: 0x8a7db90> {length = 2, path = 0 - 0}); element kind: (UICollectionElementKindSectionHeader); frame = (0 50; 320 50); zIndex = 1024;
without invalidating the layout'
Кажется, это вызвано обновлением атрибутов, как если бы я закомментировал следующие две строки, все работает нормально:
attributes.zIndex = 1024;
attributes.frame = frame;
Что вызывает эту ошибку и что я могу сделать, чтобы запустить мой простой пример?
Вот полная реализация класса для этого простого примера:
@implementation myStackedHeaderFlowLayout
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
// Call super to get elements
NSMutableArray* answer = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
// As a test, always add first header to the answer array
NSArray* indexes = [NSArray arrayWithObjects: [NSNumber numberWithInt:0], nil];
for (NSNumber* sectionNumber in indexes) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:[sectionNumber integerValue]];
UICollectionViewLayoutAttributes* layoutAttributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
if (layoutAttributes) {
[answer removeObject:layoutAttributes]; // remove if already present
[answer addObject:layoutAttributes];
}
}
return answer;
}
- (UICollectionViewLayoutAttributes*)layoutAttributesForSupplementaryViewOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath {
// Call super to get base attributes
UICollectionViewLayoutAttributes* attributes = [super layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
CGRect frame = attributes.frame;
frame.origin.y += 50;
// Update attributes position here - causes the problem
attributes.zIndex = 1024;
attributes.frame = frame;
}
return attributes;
}
- (UICollectionViewLayoutAttributes*)initialLayoutAttributesForAppearingSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath {
UICollectionViewLayoutAttributes* attributes = [self layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
return attributes;
}
- (UICollectionViewLayoutAttributes*)finalLayoutAttributesForDisappearingSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath {
UICollectionViewLayoutAttributes* attributes = [self layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
return attributes;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBound {
return YES;
}
@end