ios - Swift 3 在单元格按钮上添加选择器问题

标签 ios swift xcode swift3 selector

我的 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/

相关文章:

swift - 为什么允许我使用继承所述协议(protocol)的结构设置协议(protocol)的只读属性?

xcode - 将多个 socket 连接到单一操作?

ios - 在任何滚动或表格重新加载后,在 TableView 中使用计时器重新创建计时器

ios - 正确的segue流程

ios - App review - 指向 dev api 而不是 prod

ios - 快速 editActionsForRowAtIndexPath

ios - UIWindow 无法填满新设备的屏幕?

iOS - 在 CoreData 中保存结构数组

android - OneSignal API DELETE 调用的可能错误消息有哪些?

swift - 结合 Realm 执行异步串行请求的问题