如何获取集合视图所选项目的位置? [英] How to get position of selected item of collection view?

查看:31
本文介绍了如何获取集合视图所选项目的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中有一个用户网格.我使用集合视图制作了网格.当用户点击单元格时,我需要选定单元格的位置或框架.我已经使用了视图的触摸事件,但它在集合视图的情况下不起作用.

In my project there is a grid of users. I made grid using collection view. When user taps on cell I need position or frame of selected cell. I have used touch event of view but it's not working in the case of 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 项目时,此方法也有效.

also this method works when you touch rest of UIView expect collectionView items.

推荐答案

可以使用下面的方法获取单元格属性

You can use the following method to get the cell attributes

func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

然后使用 frame 属性获取框架

and then get the frame using frame property

let attributes = self.collectionView.layoutAttributesForItem(at:indexPath)
let frame = attributes.frame

PS- 您可能必须将单元格的框架从 UICollectionView 转换为控制器的视图才能获得其确切位置.

PS- you might have to convert the frame of the cell from UICollectionView to your controller's view to get its exact position.

func convert(_ rect: CGRect, 
    from view: UIView?) -> CGRect

应该做的伎俩

这篇关于如何获取集合视图所选项目的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆