Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UIVIew from accessibilityLabel for KIF automation

I am using the KIF Framework for functional UI testing. Let's say I am on a current iPad screen where many views (labels, buttons, textfields etc) have unique accessibility labels assigned. If I have the accessibilityLabel string handy, can I get a reference to the associated UIView from current screen using it?

For example, [[UIView alloc] viewWithTag:5] returns UIVIew of provided tag. I am looking for something like [[UIView alloc] viewWithAccessiblityLabel:@"my label"].

P.S: I know the brute-force method would be to iterate all views in self.subviews recursively, and compare accessibility label to find what am I searching for. I am looking for a better approach.

like image 556
AlienMonkeyCoder Avatar asked May 10 '13 15:05

AlienMonkeyCoder


3 Answers

There is actually an incredibly simple way to achieve what you describe when using KIF for UI automation, though KIF doesn't make it obvious that this is possible. waitForViewWithAccessibilityLabel returns a reference to the view when it is found:

Swift

 let view = tester().waitForView(WithAccessibilityLabel: "My label")

Objective-C

UIView *view = [tester waitForViewWithAccessibilityLabel:@"My label"];

Hugely useful, once discovered.

like image 119
Duncan Babbage Avatar answered Nov 15 '22 04:11

Duncan Babbage


I am using KIF for UI automation! Here are the steps to get view from given accessibilityLabel. Method viewContainingAccessibilityElement:element is extension method to UIAccessibilityElement class.

UIAccessibilityElement *element = [[[UIApplication sharedApplication] keyWindow] accessibilityElementWithLabel:label];
UIView *view = (UIView*)[UIAccessibilityElement viewContainingAccessibilityElement:element];
like image 23
AlienMonkeyCoder Avatar answered Nov 15 '22 04:11

AlienMonkeyCoder


It sounds to me (from your comment: "I need this functionality in automating UI tests") like you are looking for the accessibilityIdentifier. From the documentation:

The UIAccessibilityIdentification protocol is used to associate a unique identifier with elements in your user interface. You can use the identifiers you define in UI Automation scripts because the value of accessibilityIdentifier corresponds to the return value of the name method of UIAElement.

like image 38
David Rönnqvist Avatar answered Nov 15 '22 04:11

David Rönnqvist