Подтвердить что ты не робот

Как программно добавить заголовок в UICollectionView с помощью UICollectionViewLayout

У меня есть 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"];

Может ли кто-нибудь указать мне, где я запутался?

4b9b3361

Ответ 1

Нашел проблему, я не возвращал атрибуты моего заголовка в этом методе UICollectionLayoutView:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect; // return an array layout attributes instances for all the views in the given rect

Ответ 2

Вы просматриваете неправильный вид вида.

Ваша строка, регистрирующая класс:

[self.collectionView registerClass:[UICollectionReusableView class]
  forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
  withReuseIdentifier:@"HeaderView"];

Должно быть:

[self.collectionView registerClass:[UICollectionReusableView class]
  forSupplementaryViewOfKind: UICollectionElementKindSectionHeader
  withReuseIdentifier:@"HeaderView"];

Изменить. Похоже, ваш код используется с помощью sectionFooter. Вы пытаетесь программно добавить заголовок или нижний колонтитул?

Ответ 3

Убедитесь, что вы указали ссылочный размер заголовка в UICollectionViewFlowLayout

[flowLayout setHeaderReferenceSize:CGSizeMake(320, 50)];

и для нижнего колонтитула

[flowLayout setFooterReferenceSize:CGSizeMake(320, 50)];

Ответ 4

Ваш метод делегирования для размера ссылки на заголовки неверен, вы вызываете метод нижнего колонтитула, referenceSizeForFooterInSection, как показано ниже:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
  CGSize headerSize = CGSizeMake(320, 44);
  return headerSize;
}

Индивидуально заданный HeaderReferenceSize будет исправлять проблему с заголовком. Но приложение выйдет из строя, вы сохраните вышеуказанный метод и верните нуль в viewForSupplementaryElementOfKind для нижнего колонтитула.

Ответ 5

Я думаю, вы должны назвать это в своем методе viewdidload:

[collectionViewFlowLayout setHeaderReferenceSize:CGSizeMake(self.collectionView.frame.size.width, 50)];

Ответ 6

ваш чек:

if (kind == UICollectionElementKindSectionFooter)

Вы должны проверить: UICollectionElementKindSectionHeader

для:

dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter