之前项目中的需求:collectionView的顶部是一个视图,随着collectionView一起滚动,点击头部视图中的一个按钮,headerView的高度变高,再次点击还原。
效果图自己想象
/*
根据苹果官方文档说明,scrollView上最好不要再次添加scrollView,scrollView嵌套会比较麻烦
*/
思路:
1.自定义reusbleView,添加头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
GGAutoScrollCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerID forIndexPath:indexPath];
view.delegate = self;
return view;
}
2.通过代理方式设置headerView的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
if(self.isType == YES){ //设置一个isType 初始化时将其设置为NO,返回的高度就是300
return CGSizeMake(CGRectGetWidth(self.view.frame),500);
}
return CGSizeMake(CGRectGetWidth(self.view.frame),300);
}
3.在自定义顶部视图中添加一个代理方法
@protocol reusableViewDelegate <NSObject>
- (void)changeWithType:(BOOL)type;
@end
通过按钮的点击与否,传递状态
- (void)click:(UIButton *)sender{
sender.selected = !sender.selected;//
if([self.delegate respondsToSelector:@selector(changeWithType:)]){
[self.delegate changeWithType:sender.selected];
}
}
4.根据状态刷新整个collcetionView
- (void)changeWithType:(BOOL)type{
self.isType = type;
//通过按钮的状态,刷新数据更新headerView的高度 可自定义
[self.collectionView reloadData];
}
网友评论