如何将触摸事件发送到 iOS 上的 UIView

How to send touch event to a UIView on iOS

我在视图上添加了点击手势。当点击视图时,调用内部方法并弹出警报。

现在我想发送触摸事件来模拟此视图上的手指触摸。我该怎么做?

===============

谢谢大家

我想我应该把问题描述清楚。我在 iOS12 上研究 ReplayKit。我们可以将 RPSystemBroadcastPickerView 添加到我们的自定义视图中。在我的项目中,单击一个按钮,RPSystemBroadcastPickerView 初始化并添加到我的视图中,点击 RPSystemBroadcastPickerView,select 个项目,然后单击开始广播。

我想做的是当我点击按钮时,它会自动跳转到select项界面。就像点击按钮后向 RPSystemBroadcastPickerView 发送触摸事件一样。

您可以创建自定义视图并覆盖以下方法...

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;

Swift版本

func touchesBegan(Set<UITouch>, with: UIEvent?)

Tells this object that one or more new touches occurred in a view or window.


func touchesMoved(Set<UITouch>, with: UIEvent?)

Tells the responder when one or more touches associated with an event changed.


func touchesEnded(Set<UITouch>, with: UIEvent?)

Tells the responder when one or more fingers are raised from a view or window.


func touchesCancelled(Set<UITouch>, with: UIEvent?)

Tells the responder when a system event (such as a system alert) cancels a touch sequence.

详情请参考link.

UIButton *btnInPicker = nil;
for( UIView *_subView in self.broadcastPicker.subviews) {
    if( [_subView isKindOfClass:[UIButton class]] ) {
        btnInPicker = (UIButton *)_subView;
        break;
    }
}


if(btnInPicker) {
    [btnInPicker sendActionsForControlEvents:UIControlEventTouchDown];
}

但它有一个问题:

对 begin/end 外观转换的不平衡调用

这可能对您有所帮助。但请记住,iOS 中的触摸机制具有复杂的结构,这段代码可能不会产生您想要的结果。

targetView.touchesBegan(.init(), with: nil)
targetView.touchesEnded(.init(), with: nil)

首先,在屏幕的某个位置创建一个 RPSystemBroadcastPickerView 并且没有高度和宽度以不显示其图标并将其添加到您的控制器(对我来说是 topController)然后 select RPSystemBroadcastPickerView 的最顶层视图那是按钮,然后调用它的操作 -> theBroadcastPicker 现在应该打开而无需点击屏幕

 var  broadCastPicker = RPSystemBroadcastPickerView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
topController.view.addSubview(broadCastPicker!)
var tap = broadCastPicker?.subviews.first as! UIButton
tap.sendActions(for: .touchUpInside)