2017-08-01 121 views
0

我在集合视图单元格中有一个自定义按钮。我只是想indexPath传递给它,但我越来越 “无法识别的选择错误”Swift 3在单元格按钮上添加选择器问题

这里是我的代码

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

而且功能

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

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

+0

您可以使用委托模式或闭包。查看答案[这里](https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped/38941510# 38941510) – Paulw11

+1

您不能在目标/操作模式中使用自定义参数。唯一支持的参数是发送UI元素,按钮。 – vadian

回答

-1

您可以通过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)")  
} 
1

在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) 
}