CALayer的动态可访问性标签

时间:2013-05-07 21:17:40

标签: objective-c accessibility calayer uiaccessibility

如何使CALayer可访问?具体来说,我希望图层能够动态更改其标签,因为它可以随时更改。官方文档的sample code并不真正允许这样做。

1 个答案:

答案 0 :(得分:3)

以下假设你有一个超级视图,其图层都是类AccessableLayer,但是如果你有一个更复杂的布局,可以修改这个方案来处理它。

为了使CALayer可访问,您需要一个实现UIAccessibilityContainer方法的父视图。以下是一种建议的方法。

首先,让每个图层拥有其UIAccessibilityElement

@interface AccessableLayer : CALayer 
@property (nonatomic) UIAccessibilityElement *accessibilityElement;
@end

现在在其实现中,您可以在元素发生更改时修改它:

@implementation AccessableLayer

... self.accessibilityElement.accessibilityLabel = text;

@end

AccessableLayer永远不会创建UIAccessibilityElement,因为构造函数需要UIAccessibilityContainer。因此,超级视图创建并分配它:

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