在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