【问题标题】:How to send touch events to nextResponder in Swift如何在 Swift 中将触摸事件发送到 nextResponder
【发布时间】:2015-10-05 05:34:23
【问题描述】:

背景

我正在尝试使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)来帮助我解决这个问题。

【问题讨论】:

    标签: ios swift touch-event uiresponder


    【解决方案1】:

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

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

    更新:Swift 4.2

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

    【讨论】:

    • 这解决了我提出的问题。不幸的是,我的UICollectionViewCell 似乎仍然没有收到触摸事件。但是,除非您马上知道问题可能是什么,否则这可能需要一个新问题。
    【解决方案2】:

    mmh02 的答案已更新到 Swift 4.2

    next?.touchesBegan(touches, with: event)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多