Background
I'm trying to make a UICollectionViewCell behave like a button (ie, do an animated dim on touch). I had the idea of just filling the cell with a UIButton. The button would then take care of the visual effect of being tapped. But then I would need to pass the touch event on to the parent (the UICollectionViewCell) so that the button does not just consume the event. That way I could handle it with the collection view's didSelectItemAtPath. The problem below is my attempt to figure out how to pass the event on.
My problem
I came across this Objective-C answer for passing the touch event on:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self.nextResponder touchesBegan:touches withEvent:event];
}
However, I got stuck when I tried to convert this to Swift:
class MyButton: UIButton {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
self.nextResponder() // ???
}
}
The nextResponder method doesn't take any arguments, so how do I pass on the touch events?
I wasn't able to use related SO questions (here and here) to help me figure this out.
The nextResponder method returns an optional UIResponder?, so you can simply call touchesBegan on the returned object:
self.nextResponder()?.touchesBegan(touches, withEvent: event)
Update: Swift 4.2
self.next?.touchesBegan(touches, with: event)
mmh02's answer updated to Swift 4.2
next?.touchesBegan(touches, with: event)
来源:https://stackoverflow.com/questions/32941869/how-to-send-touch-events-to-nextresponder-in-swift