类似于表头而不是节头的UICollectionView头视图

6

是否可以创建类似于UITableView headerView的UICollectionView header view?我的意思是为整个集合视图创建标题视图,而不是为每个部分重复创建一个。就像图片1所示,我想要的是,而现在我做的是图片2。


请查看此链接:https://dev59.com/IWYr5IYBdhLWcg3wn7kc - boog
3个回答

3
我现在有了解决方案。在collectionView中添加一个子视图(subview),并使collectionView的contentInset在topImageView以下,如下所示。
    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)

但是在这里,topImageView不能滚动,也就是说,当我滚动collectionview时,topImageView不会跟着滚动。 - Anjaneyulu Battula

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)
        }
    }

1
我认为你的答案不适合我。首先,我既有分区标题又有整个collectionView的标题。如果没有分区标题,也许你的答案可以使用。但在其他情况下,这个函数中没有分区参数。所以... - C.Hugh

-1

在 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)

否则委托方法将不会被调用。

1
我觉得你的答案不适合我。首先,我既有分区标题又有整个collectionView的标题。如果没有分区标题,也许你的答案可以使用。但在其他情况下,这个函数中没有分区参数。所以... - C.Hugh
@C.Hugh,不是所有的东西都符合我们的需求。我们必须根据我们的要求进行定制。解释你遇到的问题会有所帮助。 - Praveen Gowlikar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接