简体   繁体   中英

Adding multiple buttons + receiving touchUpInside event inside UICollectionViewCell SWIFT programmatically

I am trying to build a CollectionView for a list all programmatically in Swift without using Storyboard. I was able to add a tap gesture event to the cell.

However, When I added a set of buttons to the UICollectionViewCell's contentView, the buttons do not receive any touch events.

Inside Controller

let sampleCollectionView = UICollectionView(frame: (..), collectionViewLayout: layout)

//Register the UICollectionViewCell inside UICollectionView
sampleCollectionView.registerClass(sampleCollectionViewCell.self, forCellWithReuseIdentifier: "sampleCell")

//Add Tap Gesture event to the cell area
let tap = UITapGestureRecognizer(target: self, action: "handleTapForCell:") 
sampleCollectionView.addGestureRecognizer(tap)

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

Inside CollectionViewCell

class sampleCollectionViewCell: UICollectionViewCell
{ 

 override init(frame: CGRect) {
  var buttonBack = UIButton(type: .Custom)
  buttonBack.addTarget(self, action: "actionGoBack:", forControlEvents: UIControlEvents.TouchUpInside)
  ..
  self.contentView.addSubview(buttonBack)
 }

 func actionGoBack(sender: UIButton){
    //I want to get my touch action break in here when I tap right inside the button but it won't
 }         
}

Is CollectionViewCell suited to accept more than one type of tap action (tapping on the whole cell versus multiple buttons inside cell)?

Here is what I tried so far:

  1. Disable Tap Gesture on CollectionView, still not receiving events
  2. Without adding tap events to button, I tried to find the "location" of tap inside the cell, then check if this is in bounds of the button, if so, fire an event. I find this work around to be buggy when I try to add animation or scroll.

Thanks for your suggestions and help.

You can set the gesture recognizer to not block the touches in subview

gestureRecognizer.cancelsTouchesInView = false

You can also implement UIGestureRecognizerDelegate and set yourself as delegate. Then you can implement shouldReceiveTouch

optional public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool

There you can check which view is targeted and return false if you don't want to react to the touch in the cells gesture recognizer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM