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

C J picture C J · Mar 1, 2018 · Viewed 7.3k times · Source

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?

Answer

N Brown picture N Brown · Mar 2, 2018

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)