Search code examples
iosxcode-ui-testing

Touch specific coordinate (UI tests)


How can I touch specific coordinate with UITests?

When I'm recording tap on specific place, I have something like:

XCUIApplication *app = [[XCUIApplication alloc] init];
[[[[[[[[[[app.otherElements containingType:XCUIElementTypeNavigationBar 
identifier:@"Navigation Bar title"] 
childrenMatchingType:XCUIElementTypeOther].element 
childrenMatchingType:XCUIElementTypeOther].element 
childrenMatchingType:XCUIElementTypeOther].element 
childrenMatchingType:XCUIElementTypeOther] elementBoundByIndex:0] 
childrenMatchingType:XCUIElementTypeOther].element 
childrenMatchingType:XCUIElementTypeOther] 
elementBoundByIndex:0].staticTexts[@"Action"] tap];

Solution

  • You can only tap specific coordinate referenced off of a known element. Meaning, you can't tap the pixel at coordinates (20, 400). Instead, you need to find an element and then tap something with an offset.

    XCUIApplication *app = [[XCUIApplication alloc] init];
    XCUIElement *label = app.labels[@"Label Name"];
    XCUICoordinate *coordinate = [label coordinateWithNormalizedOffset(CGVectorMake(0.5, 1.2));
    [coordinate tap];
    

    I documented more information on how to figure out the right offset in my UI Testing Cheat Sheet post.


    If you are just trying to tap the Action button you can access it directly (instead of drilling down with all of those queries).

    XCUIApplication *app = [[XCUIApplication alloc] init];
    [[[app.navigationBars element].staticTexts[@"Action"] tap];