Dynamic Accessibility Label for CALayer

最后都变了- 提交于 2019-11-29 23:11:13

问题


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;
}


来源:https://stackoverflow.com/questions/16428713/dynamic-accessibility-label-for-calayer

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