Search code examples
xcodeautomationcoordinatesui-automationxcuitest

Xcode XCUITest XCUICoordinate not working with press and/or drag


I am running Xcode 9.4.1 and trying to do long press and press & drag functions using XCUICoordinates. I have both methods working fine on XCUIElements but both failing when run against XCUICoordinates.

For example, take the following code

    let app = XCUIApplication()
    let pointOfInterest = app.buttons["PointOfInterest1"]
    let coordinates: XCUICoordinate = app.coordinate(withNormalizedOffset: CGVector(dx: pointOfInterest.frame.origin.x, dy: pointOfInterest.frame.origin.y))
    // This does nothing:
    coordinates.press(forDuration: 3)
    // This selects the points of interest:
    pointOfInterest.press(forDuration: 3)

When calling press() method against the point of interest XCUIElement everything works correctly and it is selected. When calling press() method against the XCUICoordinate of the same point of interest, nothing happens. It fails to select it.

This same inconsistency occurs with press and drag methods.

Is this a known bug in Xcode's XCUITest or am I creating the coordinates incorrectly?


Solution

  • Turns out you need to set the 0, 0 point first as a variable ('normalized') and then call the coordinates relative to that point. So the working code would look like this:

    let app = XCUIApplication()
    let pointOfInterest = app.buttons["PointOfInterest1"]
    let normalized = app.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0))
    let coordinates: XCUICoordinate = normalized.coordinate(withNormalizedOffset: CGVector(dx: pointOfInterest.frame.origin.x, dy: pointOfInterest.frame.origin.y))
    // This now works:
    coordinates.press(forDuration: 3)
    // This selects the points of interest:
    pointOfInterest.press(forDuration: 3)