【发布时间】:2018-04-18 04:50:07
【问题描述】:
我有一个自定义的集合视图布局,它似乎会产生一些错误。或者,也许我错过了一些东西。布局看起来像这样,来自here:
我的问题是我无法将居中单元格的 indexPath 传递给粉色按钮,centerCellIndexPath 的调用产生 nil。我还尝试在布局本身中预选单元格,如下所示:
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. 取视图控制器视图的中心点 - 也就是视觉中心点 2.转换成你感兴趣的view的坐标空间——也就是collection view 3. 获取给定位置存在的索引路径。
所以需要两行:
let centerPoint = self.view.convert(view.center, to: collectionView)
let indexPath = collectionView.indexPathForItem(at: centerPoint)
-> save media[indexPath.row]
这基本上是 Sachin Kishore 的建议,但一开始我并不理解他
我有点喜欢动态 indexPath 的想法,但它需要一些舍入,这是不可靠的。所以我认为convert 和indexPathForItem 是这里最好的
【问题讨论】:
-
只问finalPoint是显示在中心的单元格吗?
-
我猜是这样)如果有帮助,我可以粘贴完整的方法
-
我可以建议使用 stackoverflow.com/a/19266183/6080920 ,获取位于 CollectionView 中心的单元格的 CGPoint 并将该 CGPoint 转换为 IndexPath ,然后你会得到你想要的输出
-
这并不能解决您的解决方案,但我个人会选择动态
indexPath,例如var currentIndexPath: IndexPath。当您向左或向右(+ 或 -)滑动时更新(项目?)值 -
@MaxKraev 抱歉,我以为您在滚动时正在踩踏,但是是的,在
scrollViewDidScroll中,您可以在每次移动 X 点时更新indexPath。ceil(scrollView.contentOffset.x/(cellSize+spacing))或类似的东西。请注意,它未经测试
标签: ios swift offset collectionview cgpoint