如何在Swift中将触摸事件发送到nextResponder [英] How to send touch events to nextResponder in Swift

查看:122
本文介绍了如何在Swift中将触摸事件发送到nextResponder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使UICollectionViewCell的行为类似于按钮(即,在触摸时进行动画暗化).我有只用UIButton填充单元格的想法.然后,该按钮将照顾被点击的视觉效果.但是然后,我需要将touch事件传递给父对象(UICollectionViewCell),以便按钮不仅消耗该事件.这样,我可以使用集合视图的didSelectItemAtPath来处理它.下面的问题是我试图弄清楚如何传递事件.

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.

我遇到了此Objective-C答案,用于将触摸事件传递给:

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]; 
}

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

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() // ???
    }
}

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

The nextResponder method doesn't take any arguments, so how do I pass on the touch events?

我无法使用相关的SO问题(此处

I wasn't able to use related SO questions (here and here) to help me figure this out.

推荐答案

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

The nextResponder method returns an optional UIResponder?, so you can simply call touchesBegan on the returned object:

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

更新:Swift 4.2

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

这篇关于如何在Swift中将触摸事件发送到nextResponder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆