如何获得"绵羊"的索引?我点击了使用Swift for iOS在Xcode中创建的CollectionView?
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在TouchDown上创建了一个发送事件:
@IBAction func clickingSheep(_ sender: UIButton) {
print("This will show info about the Sheep")
print(sender)
}
但我得到的回应是第二次印刷:
<UIButton: 0x7f9a63021d20; frame = (50 50; 136 169); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x60800003d260>>
可能有一些方法可以找出点击哪只羊,但我如何获得这些信息呢?
答案 0 :(得分:4)
一种解决方案是根据按钮的位置获取单元格的索引路径。
@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
}
}
答案 1 :(得分:2)
您可以设置并检查按钮属性&#34;标记&#34; (如果您将插座设置为控制器)
这是另一个简单的解决方案:
为回调设置新属性。
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)
}