【问题标题】:Swift 3 adding selector issue on cell buttonSwift 3 在单元格按钮上添加选择器问题
【发布时间】:2017-08-01 08:24:33
【问题描述】:

我的收藏视图单元格中有一个自定义按钮。我只想将 indexPath 传递给它,但我得到了 “无法识别的选择器错误”

这是我的代码

cell.showMapButton.addTarget(self, action: #selector(testFunc(indexPath:)), for: .touchUpInside)

函数是

func testFunc(indexPath: IndexPath){
    print("Testing indexPath \(indexPath)")
}

如果我删除 indexPath 参数,它可以正常工作并且函数会被调用,但我需要该参数,所以请帮助我解决这个问题。

【问题讨论】:

  • 您可以使用委托模式或闭包。查看答案here
  • 您不能在目标/操作模式中使用自定义参数。唯一受支持的参数是发送 UI 元素,即按钮。

标签: ios swift xcode swift3 selector


【解决方案1】:

在 UIButton 的 addTarget(:action:for:) 方法中,动作最多可以接受单个 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)
}

【讨论】:

    【解决方案2】:

    您可以传递带有目标选择器参数的 UIButton 实例以进行按钮操作。

    试试下面的代码:

    添加/替换下面的代码,属于集合视图单元格到您的集合视图数据源方法 - cellForRowAtIndexPath

    cell.showMapButton.tag = indexPath.row
    cell.showMapButton.addTarget(self, action: #selector(testFunc(button:)), for: .touchUpInside)
    

    对于 Swift 4 - 使用 @objc 定义您的选择器函数,如下所示。

    @objc func testFunc(button: UIBUtton){
        print("Index = \(button.tag)")    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 2017-12-01
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      相关资源
      最近更新 更多