header
注册
private lazy var collectView:UICollectionView = {
//layout具体可以在UICollectionViewDelegateFlowLayout中重新设置
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
layout.scrollDirection = .vertical //竖直
layout.itemSize = CGSize(width: (jk_kScreenW-55)/2 , height: (jk_kScreenW-55)/2)
layout.minimumInteritemSpacing = 15 //item 间距
layout.minimumLineSpacing = 15
layout.sectionInset = .init(top: 0, left: 20, bottom: 0, right: 20)
// layout.headerReferenceSize = CGSizeMake(jk_kScreenW, 100);
let collectView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
collectView.delegate = self
collectView.dataSource = self
collectView.showsVerticalScrollIndicator = false
collectView.jk.registerCollectionReusableView(reusableView: UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader)
// collectView.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier:"111")
// collectView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell");
collectView.register(HomeAnchorListViewCell.self, forCellWithReuseIdentifier: "HomeAnchorListViewCell");
return collectView
}()
实现代理
UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var reusabView = UICollectionReusableView.init()
if kind == UICollectionView.elementKindSectionHeader {
let headerView :UICollectionReusableView = collectionView.jk.dequeueReusableSupplementaryView(reusableView: UICollectionReusableView.self, in: collectionView, ofKind: UICollectionView.elementKindSectionHeader, for: indexPath)
for v in headerView.subviews{
v.removeFromSuperview()
}
headerView.backgroundColor = .orange
reusabView = headerView
}
return reusabView
}
注册
[_collectionView registerClass:[MyCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
设置header
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
UICollectionReusableView* reusableView = nil;
if (kind ==UICollectionElementKindSectionHeader) {
UICollectionReusableView* header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
reusableView = header;
}
return reusableView;
}
设置size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
CGSize size={kMinScreenWidth,100};
return size;
}
设置悬浮
layout.sectionHeadersPinToVisibleBounds = YES;