在使用collectionView时,想做个分组,需要显示header,但是发现,显示header和footer的回调方法不执行,不懈追踪,终于找到原因!!!!!!!

    layout.headerReferenceSize = CGSizeMake(100, 22);//重要,写上该行代码后,显示header和footer的回调方法成功执行,最终成功显示header

现在记录一下CollectionView的使用过程

初始化:

   UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

 [layout setScrollDirection:UICollectionViewScrollDirectionVertical];

   layout.headerReferenceSize = CGSizeMake(100, 22);

   UICollectionView *dataListcollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64,self.view.frame.size.width,260) collectionViewLayout:layout];

    [dataListcollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];//注册cell

    [dataListcollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];//注册header的view

    dataListcollectionView.delegate = self;

    dataListcollectionView.dataSource = self;

    [self.view addSubview:dataListcollectionView];

 

 设置代理方法

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 1;

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return [dataArray count];

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    return cell;

}

 //显示header和footer的回调方法

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

{

    if (kind == UICollectionElementKindSectionHeader)

 {//如果想要自定义header,只需要定义UICollectionReusableView的子类A,然后在该处使用,注意AIdentifier要设为注册的字符串,此处为“header”

        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];

        return view;

    }

    return nil;

}

//设置元素大小

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

        return CGSizeMake(100,100);

}

 

 

posted on 2015-01-21 17:46  瓜甜甜  阅读(9297)  评论(3编辑  收藏  举报