ios - UICollectionView:ScrollToItem 到中心单元格在水平集合视图上不起作用
问题描述
我有一个带有内容偏移量的水平 UICollectionView,以便每个元素(包括最左边的项目)都可以滚动到中心:
let cvOffset = (UIScreen.main.bounds.width - tileSize) / 2
collectionView.contentInset = UIEdgeInsets(top: 0, left: cvOffset, bottom: 0, right: cvOffset)
collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: cvOffset, bottom: 0, right: cvOffset)
但是,当我使用scrollToItem
方法时,它只对右半部分有效。如果我选择左半部分的任何项目,则输入第一个单元格。你知道为什么吗?
collectionView.scrollToItem(at: IndexPath.init(row: sender.tag, section: 0), at: .centeredHorizontally, animated: true)
解决方案
不确定这是否是UICollectionView
流布局中的错误或某种期望的结果,但您可以通过将UICollectionViewFlowLayout
s设置sectionInset
为内容插图来做您需要的事情,然后scrollToItem
按预期工作:
因此,删除您的contentInset
并将以下内容添加到您的布局中:
layout.sectionInset = UIEdgeInsets(top: 0, left: cvOffset, bottom: 0, right: cvOffset)
在我的测试应用程序中,它完成了它应该做的事情,所以滚动到选定的单元格并为所有indexPath
s居中
推荐阅读
- javascript - 我可以找到关于可编辑内容的插入符号位置吗?当我按下回车键并开始写作时,它会给出关于新 div 的插入符号位置
- javascript - 如何在谷歌地图api上显示带有方向的标签
- google-cloud-platform - 不支持直接通过 Key ID 属性设置主键 - Spanner 数据库
- java - 我如何设置 setCapability testName 成为黄瓜场景
- vue.js - 如何为子文件夹构建 vue.js
- debugging - VS Code 调试器显示无限深的 PyTorch 张量
- python - 如何在二叉树中列出一个人的所有表亲
- java - 将 html 页面更改为 .png
- java - 如何使用 google ml api 修复无效范围(400 错误请求)
- rest - 单击按钮时刷新 amp-list 内容