1 自定义分组头部
@interfacePropertyHeader :UIView
@property (nonatomic, strong) UILabel *titleLabel;
@end
@implementation PropertyHeader
- (UILabel*)titleLabel{
if (!_titleLabel) {
_titleLabel= [UILabelnew];
_titleLabel.font= [UIFontsystemFontOfSize:14];
}
return _titleLabel;
}
- (instancetype)init{
self= [superinit];
if(self) {
[selfaddSubview:self.titleLabel];
[self.titleLabelmas_makeConstraints:^(MASConstraintMaker*make) {
make.left.equalTo(@10);
make.top.bottom.equalTo(self);
make.right.equalTo(@-10);
}];
}
return self;
}
@end
2.头部代理方法
- (UICollectionReusableView*)collectionView:(UICollectionView*)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath {
UICollectionReusableView *reusableView = nil;
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
for(UIView*vinview.subviews) {
[vremoveFromSuperview];
}
PropertyHeader *header = [[PropertyHeader alloc] init];
header.frame=CGRectMake(0,0,SCREEN_WIDTH,30);
[view addSubview:header];
[header mas_makeConstraints:^(MASConstraintMaker*make) {
make.top.left.right.bottom.equalTo(@0);
}];
header.titleLabel.text=_dataSource[indexPath.section][@"name"];
return view;
}else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([UICollectionReusableView class]) forIndexPath:indexPath];
[view addSubview:self.footerView];
return view;
}
return reusableView;
}
重点注意:
for(UIView*vinview.subviews) {
[v removeFromSuperview];
}
如未移除,会出现堆叠的问题。