CALayer 的动态无障碍标签 [英] Dynamic Accessibility Label for 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屋!