如何在Swift中向nextResponder发送触摸事件

3

背景

我想让一个UICollectionViewCell(集合视图单元格)表现得像一个按钮(即,在触摸时做出动画变暗)。我的想法是用一个UIButton填充单元格。按钮将处理被点击的可视效果。但是,我需要将触摸事件传递给父级(UICollectionViewCell),使按钮不会吞噬该事件。这样,我就可以使用集合视图的didSelectItemAtPath来处理它。下面的问题是我试图弄清如何传递事件的尝试。

我的问题

我找到了这个Objective-C答案来传递触摸事件:

- (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问题(这里这里)来帮助我解决这个问题。

2个回答

3
nextResponder 方法返回一个可选的 UIResponder?,因此您可以直接在返回的对象上调用 touchesBegan

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

更新:Swift 4.2

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

1
这解决了我提出的问题。不幸的是,我的UICollectionViewCell仍然似乎没有接收到触摸事件。除非你能够立即知道问题所在,否则这可能需要提出一个新问题。 - Suragch

2

mmh02的答案已更新至Swift 4.2

next?.touchesBegan(touches, with: event)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接