Dynamic Accessibility Label for CALayer

前端 未结 1 926
北荒
北荒 2021-01-03 09:51

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

相关标签:
1条回答
  • 2021-01-03 10:42

    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;
    }
    
    0 讨论(0)
提交回复
热议问题