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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (13)

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

UIBarButtonItem不实现UIAccessibilityIdentification。但是,是否有可能分配一个可访问性标识符?

提问于
用户回答回答于

你可以子类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);
    }
}
用户回答回答于

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

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

扫码关注云+社区