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:
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.