How do I make a CALayer accessible? Specifically, I want the layer to be able to change its label on the fly, since it can change at any time. The official documentation's sample code does not really allow for this.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
The following assumes that you have a superview whose layers are all of class AccessableLayer
, but if you have a more complex layout this scheme can be modified to handle that.
In order to make a CALayer
accessible, you need a parent view that implements the UIAccessibilityContainer
methods. Here is one suggested way to do this.
First, have each layer own its UIAccessibilityElement
@interface AccessableLayer : CALayer
@property (nonatomic) UIAccessibilityElement *accessibilityElement;
@end
now in its implementation, you modify the element whenever it changes:
@implementation AccessableLayer
... self.accessibilityElement.accessibilityLabel = text;
@end
The AccessableLayer never creates the UIAccessibilityElement
, because the constructor requires a UIAccessibilityContainer. So have the super view create and assign it:
#pragma mark - accessibility
// The container itself is not accessible, so return NO
- (BOOL)isAccessibilityElement
{
return NO;
}
// The following methods are implementations of UIAccessibilityContainer protocol methods.
- (NSInteger)accessibilityElementCount
{
return [self.layer.sublayers count];
}
- (id)accessibilityElementAtIndex:(NSInteger)index
{
AccessableLayer *panel = [self.layer.sublayers objectAtIndex:index];
UIAccessibilityElement *element = panel.accessibilityElement;
if (element == nil) {
element = [[UIAccessibilityElement alloc] initWithAccessibilityContainer:self];
element.accessibilityFrame = [self convertRect:panel.frame toView:[UIApplication sharedApplication].keyWindow];
element.accessibilityTraits = UIAccessibilityTraitButton;
element.accessibilityHint = @"some hint";
element.accessibilityLabel = @"some text";
panel.accessibilityElement = element;
}
return element;
}
- (NSInteger)indexOfAccessibilityElement:(id)element
{
int numElements = [self accessibilityElementCount];
for (int i = 0; i < numElements; i++) {
if (element == [self accessibilityElementAtIndex:i]) {
return i;
}
}
return NSNotFound;
}