可达性标识符是开发人员为GUI对象生成的ID,可用于自动化测试。
UIBarButtonItem
未实现UIAccessibilityIdentification
。但是,是否有可能分配可达性标识符?
可达性标识符是开发人员为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);
}
}
希望这对你有帮助。
UIBarButtonItem *btn = [[UIBarButtonItem alloc] init...;
btn.accessibilityLabel = @"Label";
如果您在内部创建了一个 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", @"")];
}
UIBarButtonItem
是一种好的解决方案。不过,根据您的需求,将accessibilityIdentifier
分配给您的UIBarButtonItem
的自定义图像可能更有意义,假设您的UIBarButtonItem
使用自定义图像。
accessibilityIdentifier
也可以与UIBarButtonItem
一起使用了。 - fabb