如何将触摸事件发送到Swift中的nextResponder

时间:2015-10-05 05:34:24

标签: ios swift touch-event uiresponder

背景

我试图让UICollectionViewCell表现得像一个按钮(即,触摸时做一个动画调暗)。我只想用UIButton填充单元格。然后按钮将处理被轻敲的视觉效果。但是我需要将触摸事件传递给父(UICollectionViewCell),以便按钮不仅仅消耗该事件。这样我就可以使用集合视图didSelectItemAtPath来处理它。下面的问题是我试图找出如何传递事件。

我的问题

我遇到this Objective-C answer来传递触摸事件:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  
    [super touchesBegan:touches withEvent:event];
    [self.nextResponder touchesBegan:touches withEvent:event]; 
}

但是,当我尝试将其转换为Swift时,我陷入了困境:

class MyButton: UIButton {

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        self.nextResponder() // ???
    }
}

nextResponder方法不接受任何参数,那么如何传递触摸事件?

我无法使用相关的SO问题(herehere)来帮助我解决这个问题。

2 个答案:

答案 0 :(得分:3)

nextResponder方法返回一个可选的UIResponder?,因此您只需在返回的对象上调用touchesBegan

self.nextResponder()?.touchesBegan(touches, withEvent: event)

更新:Swift 4.2

self.next?.touchesBegan(touches, with: event)

答案 1 :(得分:2)

mmh02的答案已更新为Swift 4.2

next?.touchesBegan(touches, with: event)