2017-08-01 53 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) 
}