Setting accessibility identifier programmatically on UIBarButtonItem

后端 未结 4 1890
轻奢々
轻奢々 2021-02-12 08:26

The accessibility identifier is a developer generated ID for GUI objects, which can be used for automation tests.

A UIBarButtonItem does not implement

4条回答
  •  忘了有多久
    2021-02-12 08:57

    You could subclass UIBarButtonItem and implement the UIAccessibilityIdentification protocol in that subclass, lets's say BarButtonWithAccesibility.

    In BarButtonWithAccesibility.h:

    @interface BarButtonWithAccesibility : UIBarButtonItem
    
    @property(nonatomic, copy) NSString *accessibilityIdentifier NS_AVAILABLE_IOS(5_0);
    

    The only (strict) requirement for adhering to this protocol is defining the accessibilityIdentifier property.

    Now in your view controller, let's say in viewDidLoad, you could set up a UIToolbar and add your subclassed UIBarButtonItem:

    #import "BarButtonWithAccesibility.h"
    
    - (void)viewDidLoad{
    
        [super viewDidLoad];
    
        UIToolbar *toolbar = [[UIToolbar alloc]  initWithFrame:CGRectMake(0, 0, 320, 44)];
    
        BarButtonWithAccesibility *myBarButton = [[BarButtonWithAccesibility alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(buttonPressed:)];
        myBarButton.accessibilityIdentifier = @"I am a test button!";
    
        toolbar.items = [[NSArray alloc] initWithObjects:myBarButton, nil];
        [self.view addSubview:toolbar];
    }
    

    And within the buttonPressed: you could verify that you have access to the accessibilityIdentifier:

    - (void)buttonPressed:(id)sender{
        if ([sender isKindOfClass:[BarButtonWithAccesibility class]]) {
            BarButtonWithAccesibility *theButton = (BarButtonWithAccesibility *)sender;
            NSLog(@"My accesibility identifier is: %@", theButton.accessibilityIdentifier);
        }
    }
    

    Hope this helps.

提交回复
热议问题