简体   繁体   English

滚动UICollectionView时如何在顶部屏幕上自定义标题视图?

[英]How to custom header view that sticky in top screen when scroll UICollectionView?

I have the header (header : UICollectionReusableView ) in my UICollectionView . 我有头(头: UICollectionReusableView )在我UICollectionView The header has 3 UIView ( UIView1 , UIView2 , UIView3 ). 标头具有3个UIView( UIView1UIView2UIView3 )。 When I set collectionLayout.sectionHeadersPinToVisibleBounds = true , the header will in top when I scroll the collection. 当我设置collectionLayout.sectionHeadersPinToVisibleBounds = true ,在滚动集合时标题将位于顶部。 And I want when the header stick in top of UICollectionView , I will hide UIView1 and UIView2 . 而且我想当标题UICollectionViewUICollectionView顶部时,我将隐藏UIView1UIView2 How can I do that? 我怎样才能做到这一点?

UICollectionView is a subclass of UIScrollView . UICollectionViewUIScrollView的子类。 This means that is you assign a delegate to it then this delegate may listen to scrollViewDidScroll(_ scrollView: UIScrollView) method which will be called every time the offset changes in your collection view. 这意味着您要为其分配一个委托,然后该委托可以侦听scrollViewDidScroll(_ scrollView: UIScrollView)方法,该方法将在每次偏移量在集合视图中更改时被调用。

On this event you will need to get all of your header views which I assume you may get by calling visibleSupplementaryViews on your collection view and check its class type. 在此事件上,您将需要获取所有标头视图,我认为您可以通过在集合视图上调用visibleSupplementaryViews并检查其类类型来获得标头视图。

If the received view is indeed your header you will need to check its frame in comparison to your collection view and see if its position is on top. 如果接收到的视图确实是您的标题,则需要检查其框架与集合视图的对比,并查看其位置是否在顶部。 To do so you may convert frame to your coordinates: 为此,您可以将框架转换为坐标:

func isHeader(headerView: UIView, onTopOfCollectionView collectionView: UICollectionView) -> Bool {
    guard let collectionSuperView = collectionView.superview else {
         return false // Collection view is not in view hierarchy. This will most likely never happen
    }
    let convertedFrame = headerView.convert(headerView.bounds, to: collectionSuperView) // Convert frame of the view to whatever is the superview of collection view
    return convertedFrame.origin.y <= collectionView.frame.origin.y // Compare frame origins
}

So I guess the whole thing would be something like: 所以我想整个事情就像这样:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    collectionView.visibleSupplementaryViews(<#My identifier here#>).forEach { view in
        if let header = view as? MyHeaderView {
            header.hideSecondaryViews = isHeader(headerView: header, onTopOfCollectionView: collectionView)
        }
    }
}

I hope this gets you on the right track. 我希望这能使您走上正确的道路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM