我有一个自定义的集合视图布局,它似乎产生了一些bug。也许我错过了什么。布局如下图所示
here
:
我的问题是我无法将居中单元格的indexPath传递给粉红色按钮,调用
centerCellIndexPath
产生零。我还尝试在布局本身中预选单元格,如下所示:
override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// item's setup ......
// ...................
let finalPoint = CGPoint(x: newOffsetX, y: proposedContentOffset.y)
// Select cell in collectionView by Default
let updatePoint = CGPoint(x: newOffsetX, y: 180)
let indexPath = collectionView!.indexPathForItem(at: updatePoint)
self.collectionView!.selectItem(at: indexPath, animated: false, scrollPosition: [])
return finalPoint
}
但它不起作用。我必须通过向上滑动手动选择单元格,用户对此很不清楚。如何在不轻触和滑动的情况下选择单元格?
如有任何建议,将不胜感激
UPD:在一夜没睡之后,多亏了Vollan,终于成功了
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let position = 2 * scrollView.contentOffset.x / collectionView.superview!.frame.width
selectedItem = Int(round(position))
}
UPD:但最好的只是变得更好。已将答案从链接转换为Swift版本
这将是更好的代码,因为它更干净、更易于阅读,所有内容偏移量计算都是多余的:
NSIndexPath *centerCellIndexPath =
[self.collectionView indexPathForItemAtPoint:
[self.view convertPoint:[self.view center] toView:self.collectionView]];
这也将是您实际的正确表示
正在尝试执行:
1、取viewcontroller视图的中心点-又名视觉中心点
2、将其转换为您感兴趣的视图的坐标空间-即集合视图
3、获取给定位置存在的indexpath。
因此需要两行:
let centerPoint = self.view.convert(view.center, to: collectionView)
let indexPath = collectionView.indexPathForItem(at: centerPoint)
-> save media[indexPath.row]
这基本上就是萨钦·基肖尔的建议,但我一开始并不理解他
我有点喜欢使用动态indexPath的想法,但它需要一些舍入,这是不可靠的。所以我想
convert
和
indexPathForItem
是这里最好的