CALayer的动态辅助功能标签 [英] Dynamic Accessibility Label for CALayer

查看:125
本文介绍了CALayer的动态辅助功能标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使CALayer可用?具体来说,我希望该图层能够随时更改其标签,因为它可以随时更改.官方文档的示例代码确实不允许这样做.

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.

推荐答案

以下内容假定您拥有一个超级视图,其所有图层均为AccessableLayer类,但是如果布局更复杂,则可以修改此方案以进行处理那个.

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.

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

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.

首先,让每一层都拥有自己的UIAccessibilityElement

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

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

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

这篇关于CALayer的动态辅助功能标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆