问题
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:
- Disable Tap Gesture on CollectionView, still not receiving events
- 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.
回答1:
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.
来源:https://stackoverflow.com/questions/33338842/adding-multiple-buttons-receiving-touchupinside-event-inside-uicollectionviewc