iOS UICollectionView 自定义section HeaderView
发布时间
阅读量:
阅读量
iOS UICollectionView 自定义section HeaderView
首先自定义一个View类继承自UICollectionReusableView类。在自定义的Head view中创建所需的UI元素如:Label组件、Button组件等。由于UICollectionReusableView类在初始化过程中不会自动加载数据的原因,在此场景下采用了Lazy Loading技术以实现部分数据的延迟加载功能。
.h
//
// HeaderReusableView.h
// TestBaseView
//
// Created by 金英杰 on 2020/11/19.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface HeaderReusableView : UICollectionReusableView
/** <#属性注释#> */
@property (nonatomic,strong) UILabel *title;
@end
NS_ASSUME_NONNULL_END
.m
//
// HeaderReusableView.m
// TestBaseView
//
// Created by 金英杰 on 2020/11/19.
//
#import "HeaderReusableView.h"
@implementation HeaderReusableView
-(UILabel *)title{
if (!_title) {
_title = [[UILabel alloc]init];
_title.frame = CGRectMake(15, 0, jSCREEN_WIDTH-30, 30);
_title.font = jFONT(14);
_title.textColor = jColorWithHex(0x333333);
_title.textAlignment = NSTextAlignmentLeft;
[self addSubview:_title];
}
return _title;
}
@end
在UICollectionView所在superview中 两个代理方法
#pragma mark - 设置表头大小
// 要先设置表头大小
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//不需要headerview的section return CGSizeMake(0, 0),其余根据需要设置
if (section==0) {
return CGSizeMake(0, 0);
}
CGSize size = CGSizeMake(jSCREEN_WIDTH, 30);
return size;
}
// 创建一个继承collectionReusableView的类,用法类比tableViewcell
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
UICollectionReusableView *reusableView = nil;
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
// 头部视图
// 代码初始化表头
[collectionView registerClass:[HeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderReusableView"];
HeaderReusableView *tempHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderReusableView" forIndexPath:indexPath];
switch (indexPath.section) {
case 0:
tempHeaderView = nil;
break;
case 1:
tempHeaderView.title.text = @"生活娱乐";
break;
case 2:
tempHeaderView.title.text = @"体育财经";
break;
case 3:
tempHeaderView.title.text = @"科教文艺";
break;
case 4:
tempHeaderView.title.text = @"其它";
break;
default:
break;
}
reusableView = tempHeaderView;
} else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
// 底部视图设置同理
}
return reusableView;
}
就这么简单。
全部评论 (0)
还没有任何评论哟~
