2016-12-06 75 views
0

所以我有一個按鈕,看起來像在收集觀察室廈門國際銀行鉛筆。集合視圖單元格按鈕不觸發動作

enter image description here

然後,我有這樣的代碼。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "groupsCollectionViewCellIdentifier", for: indexPath) as! GroupCollectionViewCell 

    //add action to the edit button 
    cell.editButton.tag = indexPath.row 
    cell.editButton.addTarget(self, action: #selector(GroupsCollectionViewController.editGroupAction), for: .touchUpInside) 

    return cell 
} 

//segue to edit group 
func editGroupAction() { 
    performSegue(withIdentifier: "editGroupSegue", sender: self) 
} 

但每當我點擊編輯按鈕。什麼都沒有發生。我不知道缺少什麼。

回答

0

你的類分配到小區,並與控制器連接的按鈕,也是標識符分配給SEGUE,還可以使用斷點檢查func被調用或不

,並使用賽格瑞這樣

​​
+0

我已經分配給小區課堂上,Segue公司也有一個標識符。 –

+0

你是否嘗試斷點,然後檢查func是否被調用 –

+0

所以在斷點中它甚至沒有調用函數。點擊按鈕什麼也不做。 –

1

考慮到您的問題,我已經創建了一個演示,其中包含上面提供的細節以及一些細微的更改。
我已修改您的cellForItem方法。我的修改版本如下。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell : GroupCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "groupsCollectionViewCellIdentifier", for: indexPath) as! GroupCollectionViewCell 


    cell.editButton.tag = indexPath.row 
    cell.editButton.addTarget(self, action: #selector(editGroupAction(sender:)), for: .touchUpInside) 

    return cell 
} 


和動作方法寫入如下:

func editGroupAction(sender: UIButton) { 
    print("Button \(sender.tag) Clicked") 
} 


從你的代碼中,我已經修改了以下內容:
1)UICollectionViewCell對象的申報之路。
2)分配方法#Selector方法到UIButton。並在最後
3)在行動方法我打印按鈕標籤。

隨着上述變化,我得到了正確的結果。我將選定的索引值作爲按鈕標記,在CONSOL中的代碼中進行了分配。我得到的輸出如下。

Button 2 Clicked 
Button 3 Clicked 
Button 4 Clicked 

我希望這會爲您的要求工作。

0

如果您使用的是iOS 10.Following工作代碼

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 


      let cell = collectionView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! YourCellClass 
cell.btnJoin.tag = (indexPath as NSIndexPath).row  
cell.btnJoin.addTarget(self, action: #selector(YourViewControllerClassName.doSomething(_:)), for: UIControlEvents.touchUpInside) 
    } 

行動

func doSomething(_ sender: UIButton) { 
      print("sender index",sender.tag) 
    } 
相關問題