【发布时间】:2021-10-05 03:30:39
【问题描述】:
我有一个 collectionView,它固定在视图控制器的顶部,没有导航栏 collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true。
它有一个粘性标题let headerLayout = cv.collectionViewLayout as? UICollectionViewFlowLayout; headerLayout?.sectionHeadersPinToVisibleBounds = true
collectionView 有 2 个部分,第一个部分没有标题,但第二个部分有标题。问题是因为 collectionView 没有固定到 safeAreaLayoutGuide.topAnchor 并且没有导航栏,当我滚动时,第二部分中的标题被固定到状态栏后面的屏幕顶部。
如何防止标题滚动到某个点之外。例如,如果我将一个按钮固定在屏幕顶部,则标题会在它碰到按钮底部时停止
myButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.contentInsetAdjustmentBehavior = .never
let secondIndexPath = IndexPath(item: 0, section: 1)
collectionView.layoutIfNeeded()
if let headerFrameInCollectionView = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: secondIndexPath), let window = UIApplication.shared.windows.first(where: \.isKeyWindow) {
let headerFrameInSuperView = collectionView.convert(headerFrameInCollectionView.frame, to: collectionView.superview)
let headerOriginY = headerFrameInSuperView.origin.y
let buttonFrame = view.convert(myButton.frame, to: window)
let bottomOfButton = buttonFrame.origin.y + buttonFrame.height
if headerOriginY == bottomOfButton {
collectionView.contentInset.top = headerOriginY // stop header from scrolling any further
} else {
collectionView.contentInset.top = 0
}
}
}
【问题讨论】:
标签: ios swift uicollectionview uiscrollview