Dynamic Accessibility Label for CALayer

拜拜、爱过 提交于 2019-11-30 16:00:16

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!