有没有办法找到XCUIElement是否有焦点?

San*_*ndy 13 ui-testing ios xcode7 xcode-ui-testing

我的一个屏幕有多个文本字段,我可以从不同的其他屏幕登陆到这个屏幕.在每种情况下,我将一个或另一个文本字段作为第一响应者.我无法编写测试来确定所需的textField是否具有焦点.

当我在控制台中打印文本字段时 -

输出:{TextField 0x131171d40:traits:146031247360,Focused,{{ 6.0,108.3 },{402.0,35.0}},value:}

但我在XCUIElement上找不到任何focus/isFocus属性.

有没有办法实现这个目标?

hri*_*.to 23

我对派对来说有点迟了:)但是从转储变量XCUIElement可以看出它有一个有趣的属性:

属性名称:hasKeyboardFocus

物业类型:TB,R

因此,您可以通过以下方式检查元素是否具有焦点:

let hasFocus = (yourTextField.value(forKey: "hasKeyboardFocus") as? Bool) ?? false
Run Code Online (Sandbox Code Playgroud)

注意:您可以使用以下扩展名转储任何NSObject子类的属性变量:

extension NSObject {
    func dumpProperties() {
        var outCount: UInt32 = 0

        let properties = class_copyPropertyList(self.dynamicType, &outCount)
        for index in 0...outCount {
            let property = properties[Int(index)]
            if nil == property {
                continue
            }
            if let propertyName = String.fromCString(property_getName(property)) {
                print("property name: \(propertyName)")
            }
            if let propertyType = String.fromCString(property_getAttributes(property)) {
                print("property type: \(propertyType)")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:属性转储,Swift 4:*

extension NSObject {
    func dumpProperties() {
        var outCount: UInt32 = 0

        let properties = class_copyPropertyList(type(of: self), &outCount)
        for index in 0...outCount {
            guard let property = properties?[Int(index)] else {
                continue
            }
            let propertyName = String(cString: property_getName(property))
            print("property name: \(propertyName)")
            guard let propertyAttributes = property_getAttributes(property) else {
                continue
            }
            let propertyType = String(cString: propertyAttributes)
            print("property type: \(propertyType)")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 出色的答案!如果您想等待具有焦点的元素,则使用谓词和期望`let focusPredicate = NSPredicate(format:“ exists == true && hasKeyboardFocus == true”)` (3认同)

lea*_*nne 6

基于@ hris.to的出色回答,我整理了这个小扩展名(也可以在Swift 4中使用)...

extension XCUIElement
{
    func hasFocus() -> Bool {
        let hasKeyboardFocus = (self.value(forKey: "hasKeyboardFocus") as? Bool) ?? false
        return hasKeyboardFocus
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 也可以是一个计算变量,如“var hasFocus: Bool { return ... }” (2认同)