Search code examples
iosswiftautomationxctestxcuitest

How can I locate an XCUIElement searching by partial label text in Swift?


I have been locating XCUIElements using this method:

app.staticTexts["Full Label Text"]

But what if I only know part of the label text? Part of the label text is generated dynamically (e.g. "Item #1", "Item #2", etc.) so I would like to search for it by finding an element that contains part of the text (e.g. searching by "Item"). Is there any method to do this in Swift?


Solution

  • You can find elements with a predicate. Use the containing(_ predicate: NSPredicate) -> XCUIElementQuery method from XCUIElementQuery.

    let predicate = NSPredicate(format: "label CONTAINS[c] 'Item'")
    let labels = XCUIApplication().staticTexts.containing(predicate)