我想实现一个类似于以下的视图层次结构,以便整个视图可以滚动:

UIScrollView


影像检视
集合视图


但是这里的很多人都说,最好使用集合视图附带的标头。我已经做到了,但是现在有了一个新问题:在滚动集合视图时,我对viewForSupplementaryElementOfKind函数中的标头单元所做的任何配置都在重复(例如:如果我以编程方式在viewForSupplementaryElementOfKind函数中创建一个新视图,当我滚动时,此视图将继续创建)

我有点明白这是因为我正在使用dequeueReusableSupplementaryView使标题出队。但是我尝试在Apple文档上进行搜索,没有其他代码可用于实例化标题视图而不使其可重用。

有什么方法可以不使用UICollectionView而创建如上所述的视图控制器?

我尝试将部分的数量设置为1,希望它只能被重用一次,但是不起作用。

编辑:还尝试使用UICollectionViewDelegateFlowLayouta并使用UICollectionView而不是UIViewController和UICollectionViewDataSource等设置标题大小。

func collectionView(_ collectionView: UICollectionView,
                                 viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
{
        switch kind {
        case UICollectionView.elementKindSectionHeader:
            guard
                let headerView = collectionView.dequeueReusableSupplementaryView(
                    ofKind: kind,
                    withReuseIdentifier: "DiscoverHeader",
                    for: indexPath) as? DiscoverHeader
                else {
                    fatalError("Invalid view type")
            }

            // Rotating arrow image
            headerView.arrowImg.transform = headerView.arrowImg.transform.rotated(by: CGFloat.pi/0.67)

            return headerView
        default:
            assert(false, "Invalid element type")
        }
}

最佳答案

为什么不在UIImageViewUICollectionViewUIScrollView

您绝对可以创建一个UIScrollView并在其中添加UIImageViewUICollectionView

但这无法按预期进行。这是因为您要将scrollView(UICollectionView)嵌入另一个scrollView中。 Scrolling collectionView垂直会妨碍外部scrollingscrollView

解:

尝试使用height方法给出header viewUICollectionViewDelegateFlowLayout's

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: 100.0) //give the height as per your requirement...
}


另外,将contentModeimageView设置为Aspect Fit / Aspect Fill

关于swift - UICollectionView的标题 View 不断重复滚动-如何创建固定的(非粘性)单个收藏 View 标题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56647235/

10-11 22:54
查看更多