如何使 CALayer 可访问?具体来说,我希望图层能够动态更改其标签,因为它可以随时更改。官方文档的示例代码并没有真正允许这样做。
问问题
2248 次
1 回答
3
以下假设您有一个超级视图,其层都是 class 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;
}
于 2013-05-07T21:17:40.107 回答