Представление заголовка UICollectionView создать программно и добавить?

Я создал UICollectionView в раскадровке и добавил представление нижнего колонтитула заголовка, которое работает нормально. Но мой вопрос заключается в том, как создать представление UICollectionViewReusable для добавления в качестве SupplementaryView программно. Я пробовал, но делегаты не вызываются. Обратите внимание, что я также установил делегат. пытался

- (void)setUpCustomCollectionView
{

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, 320, 500) collectionViewLayout:layout];

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

    self.collectionView.bounces = NO;
    self.collectionView.tag = 10;
    self.collectionView.backgroundColor = [UIColor darkGrayColor];
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];

    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;

    [self.baseScrollView addSubview:self.collectionView];
}

И в делегате

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
          viewForSupplementaryElementOfKind:(NSString *)kind
                                atIndexPath:(NSIndexPath *)indexPath
{
 if (kind == UICollectionElementKindSectionHeader) {
            UICollectionReusableView *headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"brandingHeaderView" forIndexPath:indexPath];

            UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 80)];
            view.backgroundColor = [UIColor redColor];

                 [headerView addSubview:view];

            return headerView;
        }
}

веди меня.


person Sugan S    schedule 03.04.2014    source источник


Ответы (5)


У меня только что была аналогичная проблема, когда следующий делегат не вызывался...

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

Затем я вспомнил, что когда я определял экземпляр UICollectionViewFlowLayout, я присвоил значение itemSize в соответствии со следующим кодом...

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.itemSize = CGSizeMake(106.f, 106.f);

Попробуйте также добавить к нему следующую строку для заголовка...

layout.headerReferenceSize = CGSizeMake(320.f, 30.f);
person Aman    schedule 20.09.2014

Я предполагаю, что ошибка здесь:

[UICollectionViewFlowLayout class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader

UICollectionViewFlowLayout не может быть в заголовке

Редактировать:

Чтобы это работало, вам нужен подкласс UICollectionReusableView, не забудьте переопределить свойство reuseIdentifier. Также проверьте документы:

Справочник по классу UICollectionReusableView

person sage444    schedule 03.04.2014
comment
Спасибо @ sage444, на самом деле это только UICollectionReusableView. - person Sugan S; 03.04.2014
comment
Я не знаю, работает ли он отлично, если использовать раскадровку - person Sugan S; 03.04.2014

чтобы добавить его, необходимо создать пользовательский файл пера с именем Header (Header.xib), а UILabel перетащить из библиотеки объектов и добавить в Header.xib. Затем создается пользовательский файл, подкласс UICollectionReusableView. например HeaderCollectionReusableView.swift и header.xib созданы для его просмотра, а IBOutlet метки выполняется внутри этого пользовательского класса.

person Ikechukwu Henry Odoh    schedule 21.12.2015

Чтобы программно добавить представление заголовка в UICollectionView, вам необходимо сделать следующее.

UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout alloc] init];
layout.headerReferenceSize = CGSizeMake(100.0f, 40.0f);

UICollectionView* _collectionView=[[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
[_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:UICollectionElementKindSectionHeader];

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
          viewForSupplementaryElementOfKind:(NSString *)kind
                                atIndexPath:(NSIndexPath *)indexPath

if ([kind isEqualToString:UICollectionElementKindSectionHeader]){

UICollectionReusableView *reusableView = [collectionView      dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:UICollectionElementKindSectionHeader 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= @"Top stories";
        label.textColor = [UIColor blueColor];
        [reusableView addSubview:label];
        }
        return reusableView;
    }
    return nil;
}
person Karthik damodara    schedule 16.05.2016
comment
Вы добавляете НОВЫЙ UILabel в многоразовое представление каждый раз, когда делаете это. - person Gargoyle; 12.07.2016
comment
Выделение UILabel перемещено внутрь условия if. @Gargoyle, вы можете проголосовать прямо сейчас - person Karthik damodara; 13.07.2016

person    schedule
comment
Было бы здорово, если бы вы добавили к этому ответу некоторое обоснование и объяснение написанного вами кода. - person John; 20.12.2015
comment
раздел заголовка представления коллекции является дополнительным представлением. В противном случае, чтобы добавить его, необходимо создать пользовательский файл пера, как - person Ikechukwu Henry Odoh; 21.12.2015