默认情况下,在collectionView中滚动时选择单元格

时间:2018-04-18 04:50:08

标签: ios swift offset collectionview cgpoint

我有一个自定义集合视图布局,似乎会产生一些错误。或者也许我错过了什么。布局看起来像这样,它来自here

enter image description 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.获取存在于给定位置的索引路径。

所以需要2行:

 let centerPoint = self.view.convert(view.center, to: collectionView)
 let indexPath = collectionView.indexPathForItem(at: centerPoint)
 -> save media[indexPath.row]

这基本上是Sachin Kishore所建议的,但我起初并不理解他

我有点像动态indexPath的想法,但它需要一些舍入,这是不可靠的。所以我认为convertindexPathForItem是最好的

2 个答案:

答案 0 :(得分:1)

func viewIndexPathInCollectionView(_ cellItem: UIView, collView: UICollectionView) -> IndexPath? {
    let pointInTable: CGPoint = cellItem.convert(cellItem.bounds.origin, to: collView)
    if let cellIndexPath = collView.indexPathForItem(at: pointInTable){
        return cellIndexPath
    }
    return nil

}

在按钮操作上调用此函数,并在此函数上传递按钮名称,集合视图名称

答案 1 :(得分:1)

如果您将逻辑放入scrollViewDidScroll,则可以动态更新indexPath

let position = scrollView.contentOffset.x/(cellSize+spacing)
currenIndexPath.item = position

这应该始终为您提供当前单元格indexPath。