ios - 计算动态标题大小时,在 reloadData 上重置滚动位置
问题描述
我有一个很大UIcollectionView
的自定义逻辑,在它的标题中我有另一个UICollectionView
滚动方向设置为水平。除此之外,我在该标题视图中还有其他标签。我得到这样的标题的动态高度:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let indexPath = IndexPath(row: 0, section: section)
let headerView = self.collectionView(collectionView, viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader, at: indexPath)
let desiredWidth = collectionView.frame.width > 0 ? collectionView.frame.width : UIScreen.main.bounds.width
return headerView.systemLayoutSizeFitting(CGSize(width: desiredWidth, height: UIView.layoutFittingExpandedSize.height),
withHorizontalFittingPriority: .required, // Width is fixed
verticalFittingPriority: .fittingSizeLevel) // Height can be as large as needed
}
高度计算正确,但如果我滚动水平collectionView,然后从代码中的某个地方调用reloadData,它的滚动位置会被重置。我知道这是因为let headerView = self.collectionView(collectionView, viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader, at: indexPath)
这条线而发生的,但是有没有办法让标题高度动态并且滚动不被重置?
解决方案
这个问题的解决方案是在出队时保留一个 headerView 的实例,然后在计算 header 的高度时重新使用它。
if let headerView = self.headerView {
return headerView.systemLayoutSizeFitting(
CGSize(width: desiredWidth, height: UIView.layoutFittingExpandedSize.height),
withHorizontalFittingPriority: .required, // Width is fixed
verticalFittingPriority: .fittingSizeLevel) // Height can be as large as needed
}
return CGSize(width: desiredWidth, height: 1)
推荐阅读
- javascript - 批量发送 API 调用
- javascript - 更改 HTML 文件目录后的 JavaScript 错误
- android - 我无法同时应用“Theme.AppCompat.NoTitleBar”和“colorPrimaryDark”状态栏颜色属性
- python - 仅当某个条件为真时,如何使后台任务运行?
- python - Kivy:为 Windows 打包应用程序时,Builder.load_file('*.kv') 抛出 FileNotFoundError
- git - 为什么 git 在执行 rebase-merges rebase 时不会自动重新应用冲突解决方案?
- swift - 使用扩展从字符串中删除特定字符
- python - 当我使用 numpy genfromtxt 函数将字符串转换为整数时,为什么我想要转换的都是 0
- ruby - AbstractController::DoubleRenderError(在此操作中多次调用渲染和/或重定向)
- java - 为什么 Float 和 Double 包装类在 java 中是不可变的?