如何从descendants返回的元素中按Label过滤静态文本元素?
正确过滤Label为"Draw"的StaticText方法
你的问题核心是:car.staticTexts["Draw"]默认按identifier匹配,而目标StaticText的identifier是car_view_81、label才是"Draw",所以这种写法无效。下面是两种可靠的过滤方式:
方法1:使用NSPredicate直接匹配Label
先限定在car下的StaticText集合,再用谓词过滤label:
// 获取匹配的元素 let drawText = car.staticTexts.matching(NSPredicate(format: "label == %@", "Draw")).firstMatch // 验证存在 XCTAssertTrue(drawText.exists)
如果怕字符串格式出错,也可以用闭包形式的谓词:
let drawPredicate = NSPredicate { element, _ in guard let textElement = element as? XCUIElement else { return false } return textElement.label == "Draw" } let drawText = car.staticTexts.matching(drawPredicate).firstMatch XCTAssertTrue(drawText.exists)
方法2:使用XCUIElementQuery的链式匹配
直接通过element(matching:)方法指定匹配条件,精准定位:
let drawText = car.staticTexts.element(matching: .staticText, identifier: "car_view_81", label: "Draw") XCTAssertTrue(drawText.exists)
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

