How to send touch events to nextResponder in Swift

非 Y 不嫁゛ 提交于 2019-12-07 12:06:59

问题


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.


回答1:


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)



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!