在addTarget(:操作:对的UIButton :)方法,动作最多可以接受单个的UIButton或任何它的超类的参数。如果你需要按钮的indexPath,你需要通过子类或其他方法使它成为你的UIButton的一个属性。我这样做的方法是创建的UIButton的子类,具有indexPath,因为它的属性:
class ButtonWithIndexPath: UIButton {
var indexPath:IndexPath?
}
然后加入目标为正常:
cell.showMapButton.addTarget(self, action: #selector(testFunc(button:)), for: .touchUpInside)
不要忘记设置indexPath您的按钮到其中曾经细胞是在
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! myCell
cell.button.indexPath = indexPath
...
return cell
}
而进入它的自定义子类投它的功能来读取indexPath:
func textFunc(button: UIButton) {
let currentButton = (button as! ButtonWithIndexPath)
print(currentButton.indexPath)
}
您可以使用委托模式或闭包。查看答案[这里](https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped/38941510# 38941510) – Paulw11
您不能在目标/操作模式中使用自定义参数。唯一支持的参数是发送UI元素,按钮。 – vadian