Evdzhan Mustafa
Evdzhan Mustafa

Reputation: 3735

iOS development -- check that all UI objects have accessibility label/identifier?

I am using XCode to build an iOS app. I am currently in the process of defining UI tests using the framework added just last year. In an example test I have:

XCUIApplication().segmentedControls["genderSegmentedControl"].buttons["Girl"];

The string "genderSegementedControl" is an accessibility label defined by me in its corresponding view controller as:

genderSegmentedControl.accessibilityLabel = "genderSegmentedControl";

My question is, is there any way of me writing a script, that would check all of my UI objects and verify that they have assigned accessibility label ? I can't seem to find where in Xcode I can view the internals of the story board that I am using. I would love if I could get array of all my objects, and loop through that array and assert that the .accessibilityLabel or .accessibilityIdentifier property is non nil.

I want this so that I can verify that I have actually included all of my UI components in a test. (Some sort of code coverage if you will.)

Upvotes: 3

Views: 2726

Answers (1)

BradzTech
BradzTech

Reputation: 2835

By UI Objects, you probably mean subviews, as every visible element that can be placed in a Storyboard is a subclass of UIView.

In this case, you want to get the subviews of the ViewController's View. However, doing so will only return the first level of UIViews, not nested ones. Thus, as this answer suggests, you should use a recursive algorithm.

This function should recursively loop through every UIView that is a descendant of the ViewController that this code is written in:

func checkSubviews(view: UIView) -> Bool {
    if view.accessibilityLabel == nil && view.accessibilityIdentifier == nil {
        return false
    }
    for subview in view.subviews {
        if !checkSubviews(view) {
            return false
        }
    }
    return true
}

Now calling the following function should return false if there are any UIViews (including the view controller's view itself) that lack both an accessibilityLabel and a accessibilityIdentifier:

checkSubviews(self.view)

Upvotes: 2

Related Questions