2017-08-01 9 views
0

コレクションビューのセルにカスタムボタンがあります。ここでSwift 3セレクタのセルボタンの追加

は私のコード

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

と機能である私はちょうどそれにindexPathを渡したいが、私は 「の未認識セレクタエラー」を取得しています私が削除した場合

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インスタンスを渡すことができます。スウィフト4についてはcellForRowAtIndexPath

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

- - あなたのコレクションビューのデータソースメソッドにコレクションビューのセルに属し、コードの下に置き換え

の追加/ @objcを使用して、セレクタ機能を定義します。

は、次のコードを使用してみてください、以下のように。アクション::のために:) UIButtonするための方法であって、アクションが多くて、パラメータとして単一UIButtonまたはそれのスーパークラスのいずれかを受け入れることができaddTarget(で

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

。ボタンのindexPathが必要な場合は、サブクラスまたは他の手段でUIButtonのプロパティにする必要があります。その後、通常通りターゲットを追加

class ButtonWithIndexPath: UIButton { 
    var indexPath:IndexPath? 
} 

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

はそれにあなたのボタンのindexPathを設定するために忘れてはならない、それを行うための私の方法は、それが財産だとしてindexPathを持ってUIButtonのサブクラスを作成することです今までそれが

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) 
} 
関連する問題