Ответ 1
Нашел проблему, я не возвращал атрибуты моего заголовка в этом методе UICollectionLayoutView:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect; // return an array layout attributes instances for all the views in the given rect
У меня есть UICollectionView
в одном из моих viewcontroller
. В моем представлении коллекции используется подкласс UICollectionViewLayout
(custom) для компоновки ячеек. Во-первых, как только я выберу Layout as Custom в выпадающем меню на Storyboard, опция выбора дополнительных просмотров исчезнет.
Я попытался сделать это программно, как показано ниже, но никто из методов делегата не вызван.
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if (kind == UICollectionElementKindSectionHeader) {
UICollectionReusableView *reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
if (reusableview==nil) {
reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
}
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
label.text=[NSString stringWithFormat:@"Recipe Group #%li", indexPath.section + 1];
[reusableview addSubview:label];
return reusableview;
}
return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
CGSize headerSize = CGSizeMake(320, 44);
return headerSize;
}
В моем методе viewDidLoad у меня есть
[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
Может ли кто-нибудь указать мне, где я запутался?
Нашел проблему, я не возвращал атрибуты моего заголовка в этом методе UICollectionLayoutView:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect; // return an array layout attributes instances for all the views in the given rect
Вы просматриваете неправильный вид вида.
Ваша строка, регистрирующая класс:
[self.collectionView registerClass:[UICollectionReusableView class]
forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
withReuseIdentifier:@"HeaderView"];
Должно быть:
[self.collectionView registerClass:[UICollectionReusableView class]
forSupplementaryViewOfKind: UICollectionElementKindSectionHeader
withReuseIdentifier:@"HeaderView"];
Изменить. Похоже, ваш код используется с помощью sectionFooter. Вы пытаетесь программно добавить заголовок или нижний колонтитул?
Убедитесь, что вы указали ссылочный размер заголовка в UICollectionViewFlowLayout
[flowLayout setHeaderReferenceSize:CGSizeMake(320, 50)];
и для нижнего колонтитула
[flowLayout setFooterReferenceSize:CGSizeMake(320, 50)];
Ваш метод делегирования для размера ссылки на заголовки неверен, вы вызываете метод нижнего колонтитула, referenceSizeForFooterInSection, как показано ниже:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
CGSize headerSize = CGSizeMake(320, 44);
return headerSize;
}
Индивидуально заданный HeaderReferenceSize будет исправлять проблему с заголовком. Но приложение выйдет из строя, вы сохраните вышеуказанный метод и верните нуль в viewForSupplementaryElementOfKind для нижнего колонтитула.
Я думаю, вы должны назвать это в своем методе viewdidload
:
[collectionViewFlowLayout setHeaderReferenceSize:CGSizeMake(self.collectionView.frame.size.width, 50)];
ваш чек:
if (kind == UICollectionElementKindSectionFooter)
Вы должны проверить: UICollectionElementKindSectionHeader
для:
dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter