在UIBarButtonItem上以编程方式设置辅助功能标识符

时间:2013-12-12 12:37:44

标签: ios objective-c automation accessibility

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

UIBarButtonItem未实现UIAccessibilityIdentification。但是,我是否可以分配可访问性标识符?

4 个答案:

答案 0 :(得分:15)

你可以继承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);
    }
}

希望这有帮助。

答案 1 :(得分:4)

从iOS 5开始,您可以这样做:

UIBarButtonItem *btn = [[UIBarButtonItem alloc] init...;
btn.accessibilityLabel = @"Label";

答案 2 :(得分: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", @"")];
    }

答案 3 :(得分:2)

子类化UIBarButtonItem是一个很好的解决方案。但是,根据您的需要,假设accessibilityIdentifier使用自定义图片,将UIBarButtonItem简单地分配到UIBarButtonItem的自定义图片可能更有意义。