Ios 获取UICollectionView中单击的UICollectionViewCell的索引
如何获取我在iOS版Swift的Xcode制作的CollectionView中单击的“绵羊”的索引Ios 获取UICollectionView中单击的UICollectionViewCell的索引,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,如何获取我在iOS版Swift的Xcode制作的CollectionView中单击的“绵羊”的索引 class SheepsOverviewVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UIC
class SheepsOverviewVC:
UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "class", for: indexPath) as! ClassesCollectionCell
if(sheeps.count > 0) {
cell.ClassImageView.image = UIImage(named: sheeps[indexPath.row] as! String)
cell.SheepName.text = names[indexPath.row] as? String
}
return cell
}
我通过Gui在着陆时创建了一个发送事件:
@IBAction func clickingSheep(_ sender: UIButton) {
print("This will show info about the Sheep")
print(sender)
}
但我得到的回应来自第二张照片:
也许有某种方法可以确定哪些羊被点击了,但是我如何获得这些信息呢
这就是它的样子(其他名称随后在文章中提供):
一种解决方案是根据按钮的位置获取单元格的索引路径
@IBAction func clickingSheep(_ sender: UIButton) {
let hitPoint = sender.convert(CGPoint.zero, to: collectionView)
if let indexPath = collectionView.indexPathForItem(at: hitPoint) {
// use indexPath to get needed data
}
}
您可以设置并检查按钮属性“标记”(如果您将插座设置为控制器) 下面是另一个简单的解决方案: 具有回调的新属性
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "class", for: indexPath) as! ClassesCollectionCell
if(sheeps.count > 0) {
cell.ClassImageView.image = UIImage(named: sheeps[indexPath.row] as! String)
cell.SheepName.text = names[indexPath.row] as? String
}
cell.callBack = { [weak self] collectionViewCell in
let indexPath = collectionView.indexPath(for: collectionViewCell)
self?.doStuffFor(indexPath)
}
return cell
}
在手机上你可以进行ibaction
cell class
//...
var callBack : ((UICollectionViewCell?)->Void)?
//...
@IBAction func action(_ sender: UIButton) {
self.callBack?(self)
}
clickingSheep
方法是在自定义单元格类中还是在集合视图控制器类中?假设在创建集合视图的位置定义了clickingSheep
:可能与@OzgurVatansever no重复,它不是UiTableView。@maddy在collectionviewcontrollerclass@user1469734好啊那么Ozgur的链接基本上就是您所需要的。只需稍微调整一下用于UICollectionView
的API,而不是UITableView
。不,不要向单元格添加indexPath
属性。在“集合”视图中删除、插入或移动项目时,该选项都是错误的。最好将单元格而不是indexPath作为参数传递给回调函数。然后处理程序可以询问集合视图单元格的索引路径是什么。更新响应。用于观察的Thx@rmaddy。