我的 Collection View 单元格中有一个自定义按钮。我只想将 indexPath 传递给它,但我得到了 “无法识别的选择器错误”
这是我的代码
cell.showMapButton.addTarget(self, action: #selector(testFunc(indexPath:)), for: .touchUpInside)
函数是
func testFunc(indexPath: IndexPath){
print("Testing indexPath \(indexPath)")
}
如果我删除indexPath参数,它工作正常并且函数被调用,但我需要该参数,所以请帮助我解决这个问题。
最佳答案
在 UIButton 的 addTarget(:action:for:) 方法中,操作最多可以接受单个 UIButton 或其任何父类(super class)作为参数。如果您需要按钮的indexPath,则需要通过子类或其他方式将其设为UIButton 的属性。我的方法是创建一个 UIButton 的子类,其属性为 indexPath:
class ButtonWithIndexPath: UIButton {
var indexPath:IndexPath?
}
然后照常添加目标:
cell.showMapButton.addTarget(self, action: #selector(testFunc(button:)), for: .touchUpInside)
不要忘记将按钮的索引路径设置为其所在单元格的索引路径
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)
}
关于ios - Swift 3 在单元格按钮上添加选择器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45432615/