gpt4 book ai didi

ios - 如何获取 Collection View 中所选项目的位置?

转载 作者:搜寻专家 更新时间:2023-11-01 05:49:21 25 4
gpt4 key购买 nike

在我的项目中有一个用户网格。我使用 Collection View 制作了网格。当用户点击单元格时,我需要所选单元格的位置或框架。我使用了 View 的触摸事件,但它在 Collection View 的情况下不起作用。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let location = touch.location(in: self.view)
print(location)
}

当您触摸 UIView 的其余部分时,此方法也适用于 collectionView 项目。

最佳答案

基本上,您需要使用:

let cPoint = collectionView.layoutAttributesForItem(at indexPath: IndexPath).center

但之后你需要像这样将点转换为 View 的坐标系:

let centerPoint = collectionView.convert(center ?? CGPoint.zero, to: collectionView.superview)

这是一个完整的代码片段:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let attributes = self.collectionView?.layoutAttributesForItem(at:indexPath)
let cPoint = attributes?.center

/*
this is nice. but when we scroll passed the visible items -
we see that the point is given in the collectionView's coordinates.

we need to convert the point to the collectionView.superview coordinate system
*/
//solution:
let centerPoint = collectionView.convert(cPoint, to: collectionView.superview)
}

关于ios - 如何获取 Collection View 中所选项目的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54529534/

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