ios - 滚动 UICollectionView 时如何自定义在顶部屏幕上粘滞的标题 View ?

标签 ios swift uicollectionview

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

最佳答案

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/

相关文章:

ios - UICollectionViewCell 索引号不准确

swift - 找不到委托(delegate)方法索引路径

ios - UICollectionView 动画,类似于 Google Play 新闻应用

ios - 将图像调整为适合纵横比

ios - 如何确定 UITableView 性能低下的原因

ios - TableView 单元格和 TableView 标题 View 的大小

ios - CLGeoCoder 没有以正确的顺序附加地标

objective-c - 从 Objective-c 项目访问时找不到某些 Swift 类属性

javascript - 当用户在文本框外单击时隐藏在 iOS 键盘中

ios - admob 广告被关闭后执行 segue