首页 > 解决方案 > 以编程方式在屏幕上执行点击

问题描述

有没有办法以编程方式在屏幕上执行点击?

我需要通过用户点击访问无法以编程方式访问的框架按钮。

因此,我需要在用户点击屏幕时模拟点击,该位置的组件会响应,例如按钮。

标签: iosswiftscreentap

解决方案


这是我在测试中使用的东西:

class TouchMock: UITouch {
    var y: CGFloat

    init(y: CGFloat) {
        self.y = y
        super.init()
    }

    override func location(in view: UIView?) -> CGPoint {
        return CGPoint(x: 10, y: y)
    }
}

func sendTouchesBegan(y: CGFloat, to view: UIView) {
    let touch = TouchMock(y: y)
    view.touchesBegan([touch], with: nil)
}

func sendTouchesMoved(y: CGFloat, to view: UIView) {
    let touch = TouchMock(y: y)
    view.touchesMoved([touch], with: nil)
}

func sendTouchesEnded(y: CGFloat, to view: UIView) {
    let touch = TouchMock(y: y)
    view.touchesEnded([touch], with: nil)
}

func sendTouchesCancelled(y: CGFloat, to view: UIView) {
    let touch = TouchMock(y: y)
    view.touchesCancelled([touch], with: nil)
}

重要提示:对我来说,只有 Y 坐标很有趣。添加 X 坐标当然是微不足道的。


推荐阅读