2016-07-08 132 views
0

在我的Swift代碼中,我有一個帶有3個按鈕的UICollectionViewCell(這三個按鈕都有IBAction)。從我的UICollectionViewController我現在想要「抓住」單個按鈕水龍頭。找出UICollectionView單元中的多個按鈕中的哪一個被點擊

我已經按照這個StackOverflow question,我可以趕上UICollectionViewCell的觸摸式內部在我CollectionViewController與加入這行來viewDidLoad中

gestureRecognizer.cancelsTouchesInView = false 

,並用此功能

func handleTapForCell(recognizer: UITapGestureRecognizer){ 
    //I can break in here 
} 

但現在失蹤的作品是我怎樣才能找出三個按鈕中的哪一個被點擊了?我已經在按鈕上設置了不同的標籤,但是在處理這些標籤的gestureRecognizer上我還沒找到任何地方。

任何想法?

+0

因此您想要檢測哪個子視圖是從handleTapForCell中點擊的?如果是的話,這是客觀的答案,應該可以幫助你。 http://stackoverflow.com/questions/38225747/uitapgesturerecognizer-for-detecting-which-uiview-was-tapped-on-my-screen/38226252#38226252 –

+0

但爲什麼使用點擊手勢而不是IBAction的按鈕? –

回答

1

我想,你不需要在單元格上添加手勢來獲得tableviewCell的按鈕動作。此代碼可能會對您有所幫助:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     //Your tableviewCell code here 

     //set tag of cell button 
     cell.button1.tag = 1 
     cell.button2.tag = 2 
     cell.button3.tag = 3 

     //add action of your cell button 
     cell.button1.addTarget(self, action: Selector("cellButtonTapped:event:"), forControlEvents: .TouchUpInside) 
     cell.button2.addTarget(self, action: Selector("cellButtonTapped:event:"), forControlEvents: .TouchUpInside) 
     cell.button3.addTarget(self, action: Selector("cellButtonTapped:event:"), forControlEvents: .TouchUpInside) 

     // return cell 
    } 

    func cellButtonTapped(sender:UIButton, event:AnyObject){ 

     let touches: NSSet = event.allTouches()! 
     let touch = touches.anyObject() 
     let currentTouchPosition: CGPoint = (touch?.locationInView(YOUR_TABLEVIEW_INSTANCE))! 

     if let indexPath: NSIndexPath = self.YOUR_TABLEVIEW_INSTANCE.indexPathForRowAtPoint(currentTouchPosition)!{ 

      if sender.tag == 1{ 
       //cell first button tap 
      }else sender.tag == 2{ 
       //cell second button tap 
      } 
      else sender.tag == 3{ 
       //cell 3rd button tap 
      } 
     } 
    } 
+0

這對我有用。超酷。謝謝。爲了防止有人想使用它與Swift 2:我更新了選擇器行'cell.button1.addTarget(self,action:#selector(MyViewController.buttonTapped(_:event:「)),forControlEvents:.TouchUpInside) ' 並在一個CollectionView中改變indexPathForRowAt點爲 'if let indexPath:NSIndexPath = self.collectionView.indexPathForItemAtPoint(currentTouchPosition)!{' –

1

您可以遵循協議/委託範例。

你需要做的是在自定義單元中定義一個協議。然後讓viewcontroller訂閱單元委託。

在自定義單元類內實現IBActions。在按鈕的IBActions中調用委託方法。爲單元委派的viewcontroller將收到單元內按鈕水龍頭的回調。

相關問題