以编程方式在UIBarButtonItem上设置可访问标识符

23

可达性标识符是开发人员为GUI对象生成的ID,可用于自动化测试。

UIBarButtonItem未实现UIAccessibilityIdentification。但是,是否有可能分配可达性标识符?

4个回答

18

您可以对UIBarButtonItem进行子类化,并在该子类中实现UIAccessibilityIdentification协议,比如说BarButtonWithAccesibility

BarButtonWithAccesibility.h文件中:

@interface BarButtonWithAccesibility : UIBarButtonItem<UIAccessibilityIdentification>

@property(nonatomic, copy) NSString *accessibilityIdentifier NS_AVAILABLE_IOS(5_0);

遵守此协议的唯一(严格)要求是定义accessibilityIdentifier属性。

现在在您的视图控制器中,比如在viewDidLoad中,您可以设置一个UIToolbar并添加您的子类化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];
}

buttonPressed: 内部,你可以验证你是否能够访问 accessibilityIdentifier

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

希望这对你有帮助。


9
似乎iOS 8修复了这个问题,现在accessibilityIdentifier也可以与UIBarButtonItem一起使用了。 - fabb
@fabb - iOS 8中的脚本中未显示表视图单元格。你有什么想法吗? - Sandeep
它与_Appium Inspector_不兼容。它将'BarButtonWithAccesibility'(和'UIBarButtonItem')显示为'UIAButton',并将名称设置为图标文件名。 - Radek Wilczak

5
从 iOS 5 开始,您可以像这样完成:
UIBarButtonItem *btn = [[UIBarButtonItem alloc] init...;
btn.accessibilityLabel = @"Label";

辅助标识符和标签是相同的吗? - Chris
我不确定你的意思,但我会尝试翻译:默认情况下它是nil,你必须自己设置。 - Stas Zhukovskiy
你可以使用标签而不是可访问性,并且可以从标签获取对象。 - Aklesh Rathaur
9
标识符与标签不同。如果我要本地化元素,则标签可能会更改,但您希望标识符保持相同-这在自动化测试使用可访问性来标识UI元素的情况下很常见。 - tyler

3

如果您在内部创建了一个 UIToolbar ,并且想要通过编程方式创建多个 UIBarButtonItem,则可以像下面这样访问并设置accessibilityLabel

    -(void)viewDidAppear:(BOOL)animated
    {
        UIBarButtonItem *infoButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"info" style:UIBarButtonItemStyleBordered  target:self action:@selector(infoButtonClicked)];
        [self.customToolBar setItems:[NSArray arrayWithObject:infoButtonItem]];
//Here if you have muliple you can loop through it 
       UIView *view = (UIView*)[self.customToolBar.items objectAtIndex:0];
    [view setAccessibilityLabel:NSLocalizedString(@"Test", @"")];
    }

2
子类化UIBarButtonItem是一种好的解决方案。不过,根据您的需求,将accessibilityIdentifier分配给您的UIBarButtonItem的自定义图像可能更有意义,假设您的UIBarButtonItem使用自定义图像。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接