2016-07-08 8 views
0

私のSwiftコードでは、UICollectionViewCellに3つのボタン(3つともIBActionsがあります)があります。私のUICollectionViewControllerから、私は今、個々のボタンタップを "キャッチ"したいと思います。UICollectionViewセルの複数のボタンのうちどれがタップされたのかを調べる

私はこのStackOverflow question続いていると私は、この関数のviewDidLoad

gestureRecognizer.cancelsTouchesInView = false 

にとして、この行を追加することで、私のCollectionViewControllerで最大内部UICollectionViewCellのタッチアップをキャッチすることができます

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

しかし、今欠けている部分はですどのように3つのボタンのどれがタップされたのかわかります?私はボタンに別のタグを設定しましたが、これらのタグを扱うジェスチャーレコグナイザ上の場所は見つかりませんでした。

アイデア?

+0

handleTapForCellからどのサブビューがタップされたかを検出したいのですか?はいの場合はここにあなたを助けるべき客観的なCの答えです。 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:#select(MyViewController.buttonTapped(_:event:"))、forControlEvents:.TouchUpInside)を更新しました。 ' とCollectionViewでindexPathForRowAt点を で変更する場合' if indexPath:NSIndexPath = self.collectionView.indexPathForItemAtPoint(currentTouchPosition)!{' –

1

プロトコル/デリゲートのパラダイムに従うことができます。

カスタムセルでプロトコルを定義するだけです。次に、viewcontrollerをセルデリゲートに登録します。

カスタムセルクラス内でIBActionsを実装します。ボタンのIBActionsでデリゲートメソッドを呼び出します。セルを委譲するViewControllerは、セル内のボタンタップのコールバックを受け取ります。

関連する問題