gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:13 26 4
gpt4 key购买 nike

我有一个自定义的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com