Is there a way to find if the XCUIElement has focus or not?

后端 未结 5 1446
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 01:53

One of my screen has multiple text fields, I can land to this screen from different other screens. In each case I am making one or another text field as first responder. I a

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 02:12

    I little bit late for the party :) However as far as I can see from dumping the variable XCUIElement it has one interesting property:

    property name: hasKeyboardFocus

    property type: TB,R

    So you can check if your element has focus the following way:

    let hasFocus = (yourTextField.value(forKey: "hasKeyboardFocus") as? Bool) ?? false
    

    NB: you can dump the property variables of any NSObject sublass with following extension:

    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)")
                }
            }
        }
    }
    

    Update: Properties dump, 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)")
            }
        }
    }
    

提交回复
热议问题