OGeek|极客世界-中国程序员成长平台

标题: ios - 滚动UICollectionView时如何自定义顶部屏幕上的标题 View ? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:36
标题: ios - 滚动UICollectionView时如何自定义顶部屏幕上的标题 View ?

我的 UICollectionView 中有标题(标题:UICollectionReusableView)。 header 有 3 个 UIView(UIView1UIView2UIView3)。当我设置 collectionLayout.sectionHeadersPinToVisibleBounds = true 时,当我滚动集合时标题将位于顶部。我希望当标题贴在 UICollectionView 顶部时,我将隐藏 UIView1UIView2。我怎样才能做到这一点?



Best Answer-推荐答案


UICollectionViewUIScrollView 的子类。这意味着如果您为其分配了一个委托(delegate),那么该委托(delegate)可能会监听 scrollViewDidScroll(_ scrollView: UIScrollView) 方法,该方法将在每次 Collection View 中的偏移量发生变化时被调用。

在此事件中,您需要获取所有标题 View ,我假设您可以通过在 Collection View 上调用 visibleSupplementaryViews 并检查其类类型来获取这些 View 。

如果收到的 View 确实是您的标题,您将需要检查其框架与您的 Collection View 相比,并查看其位置是否在顶部。为此,您可以将框架转换为您的坐标:

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
}

所以我猜整个事情会是这样的:

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

我希望这能让你走上正轨。

关于ios - 滚动UICollectionView时如何自定义顶部屏幕上的标题 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276662/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4