UI Tests - isSelected is always returning false

I made a few tests and a little research. You can check out the app created for this purpose >>here<<. It would be great if you could check it out (it required a little bit of work). There are also UI tests to prove it works. Also, two options are available, one is vanilla XCTest and one library with a lot of helpers I'm creating with my colleagues AutoMate. But that's not the point.

Here is what I found out:

1) isSelected property of XCUIElement depends on accessibilityTrait. Element to be selected in XCTest has to have UIAccessibilityTraitSelected set.

2) I couldn't reproduce Your problem but I was able to control isSelected property.

3) Yes, it requires a little bit of code, but should work well with VoiceOver if it is important for You.

All necessary code is in Your custom UITableViewCell subclass. And uses overriding UIAccessibilityElement accessibilityTraits property.

private var traits: UIAccessibilityTraits = UIAccessibilityTraitNone

// MARK: UITableViewCell life cycle
override func awakeFromNib() {
    super.awakeFromNib()
    traits = super.accessibilityTraits
}

// MARK: UIAccessibilityElement
override var accessibilityTraits: UIAccessibilityTraits {
    get {
        if isSelected {
            return traits | UIAccessibilityTraitSelected
        }
        return traits
    }

    set {
        traits = newValue
    }
}

Hope it helps.


Couldn't get that code to compile under Swift 4. This worked for me.

public override var accessibilityTraits: UIAccessibilityTraits {
    get {
        if isSelected {
            return super.accessibilityTraits.union(.selected)
        }
        return super.accessibilityTraits
    }

    set {
        super.accessibilityTraits = newValue
    }
}