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

标签 ios swift offset collectionview cgpoint

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

enter image description 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 版本的转换答案

This would be better code because it's cleaner and easier to read, all the content offset calculation is superfluous:

 NSIndexPath *centerCellIndexPath = 
[self.collectionView indexPathForItemAtPoint:
[self.view convertPoint:[self.view center] toView:self.collectionView]];

This would also be the correct representation of what you're actually trying to do: 1. Taking the center point of your viewcontroller's view - aka visual center point 2. convert it to the coordinate space of the view you're interested in - which is the collection view 3. Get the indexpath that exist at the location given.

所以需要两行:

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

这基本上就是 Sachin Kishore 的建议,但一开始我不理解他

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

最佳答案

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

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

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

关于ios - 默认情况下在 collectionView 中滚动时选择单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49891391/

相关文章:

python - 将 matplotlib 偏移表示法从科学更改为简单

ios - typedef struct 并声明结构变量

ios - 如何使用 iCloud 同步 iOS 和 OS X 应用程序?

ios - 如何发送符合 UIImagePickerControllerDelegate、UINavigationControllerDelegate 的 UIViewController

ios - 无法访问我的单元格内容中的变量

regex - Perl Regex - 获取所有匹配项的偏移量而不是一个

ios - 有没有办法在 iOS 中通过短信或其他应用程序发送链接?

ios - 单个 UIViewcontroller 中的两个 UITableView 无法正常工作

iOS 网络/ native 应用程序 Facebook 登录弹出窗口 - 失败?

sql - Postgres - 顺序的位置是否重要?