简体   繁体   中英

Perform tap on screen programmatically

Is there a way to perform a tap on screen programmatically?

I need to access a button of a framework that is not accessible programmatically, just by the user tap.

So, I need to simulate a tap as the user was tapping the screen, and the component in that position will respond, a button for example.

Here's something I used in tests:

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)
}

Important: For me only the Y-coordinate was interesting. Adding X-coordinate is trivial of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM