辅助功能:ScrollView 自动滚动到点击时不可见的视图 "TAB"

Accessibility: ScrollView to auto scroll to the view which are not visible on hitting "TAB"

有人可以告诉我当仅使用键盘的用户尝试使用“Tab”键在 ScrollView 中的不同 UI 元素之间导航时如何自动滚动 scrollView 吗?当我按下 "TAB" 键时,焦点转移到滚动视图中存在的不同 UI 元素,但如果可见内容视图中不存在 UI 元素,它不会滚动。这怎么能实现。帮助将不胜感激。谢谢

解决方案 A:创建 NSWindow 的子类并覆盖 makeFirstResponder:makeFirstResponder 当第一响应者改变时调用。

- (BOOL)makeFirstResponder:(NSResponder *)responder {
    BOOL madeFirstResponder = [super makeFirstResponder:responder];
    if (madeFirstResponder) {
        id view = [self firstResponder];
        // check if the new first responder is a field editor
        if (view && [view isKindOfClass:[NSTextView class]] && [view isFieldEditor])
            view = [view delegate]; // the control, usually a NSTextField
        if (view && [view isKindOfClass:[NSControl class]] && [view enclosingScrollView]) {
            NSRect rect = [view bounds];
            rect = NSInsetRect(rect, -10.0, -10.0); // add a margin
            [view scrollRectToVisible:rect];
        }
    }
    return madeFirstResponder;
}

解决方案 B:创建 NSTextField 和其他控件的子类并覆盖 becomeFirstResponder

- (BOOL)becomeFirstResponder {
    BOOL becameFirstResponder = [super becomeFirstResponder];
    if (becameFirstResponder) {
        if ([self enclosingScrollView]) {
            NSRect rect = [self bounds];
            rect = NSInsetRect(rect, -10.0, -10.0); // add a margin
            [self scrollRectToVisible:rect];
        }
    }
    return becameFirstResponder;
}