3

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.

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

2 Answers2

3

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
  • 164
  • 7
  • 1
    This solves the question that I asked. Unfortunately, my `UICollectionViewCell` still doesn't appear to be receiving the touch events. Unless you know what the problem may be right off hand, though, this probably calls for a new question. – Suragch Oct 05 '15 at 07:06
2

mmh02's answer updated to Swift 4.2

next?.touchesBegan(touches, with: event)
Geoff H
  • 3,107
  • 1
  • 28
  • 53