是否可以创建类似于UITableView headerView的UICollectionView header view?我的意思是为整个集合视图创建标题视图,而不是为每个部分重复创建一个。就像图片1所示,我想要的是,而现在我做的是图片2。
是否可以创建类似于UITableView headerView的UICollectionView header view?我的意思是为整个集合视图创建标题视图,而不是为每个部分重复创建一个。就像图片1所示,我想要的是,而现在我做的是图片2。
topImageView.frame = CGRect(x: 5*SCREEN_SCALE, y: -125*SCREEN_SCALE, width: 285*SCREEN_SCALE, height: 120*SCREEN_SCALE)
collectionView.addSubview(topImageView)
collectionView.contentInset = UIEdgeInsets(top: 130*SCREEN_SCALE, left: 0, bottom: 0, right: 0)
当我想要实现这个目标时,我使用的是一个解决方法。在设置标题大小时,我会先检查节号,如果是第一节,我会相应地设置高度 - 否则我将高度设置为0,以便它不可见。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: view.frame.width, height: 35)
} else {
return CGSize(width: view.frame.width, height: 0)
}
}
在 Swift 中,像下面这样:
注册表头视图
collectionView.registerClass(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView")
在UICollectionViewDelegate中
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if section == 0 {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView", forIndexPath: indexPath)
headerView.frame.size.height = 100
return headerView }
else {
return nil
}
}
flowLayout.headerReferenceSize = CGSize(width: self.collectionView.frame.width, height: 100)