【问题标题】:Accessibility: ScrollView to auto scroll to the view which are not visible on hitting "TAB"辅助功能:ScrollView 自动滚动到点击“TAB”时不可见的视图
【发布时间】:2017-12-14 10:21:10
【问题描述】:

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

【问题讨论】:

  • 你想滚动代码吗?你有没有尝试过?
  • 是的。我希望只要视图获得焦点并且不在scrollView的可见区域中,滚动就会自动发生。我试过autoscroll: 失败了。我不知道我要做什么。希望你有我的要求。请发表评论。
  • 试试[view scrollRectToVisible:view.bounds]
  • 我试过用这个。它不起作用。我还尝试了makeFirstResponder:,这样它就可以聚焦 UI 元素,但它不会滚动。您能否提供一个描述解决方案的示例项目。

标签: cocoa accessibility nsscrollview


【解决方案1】:

解决方案 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;
}

【讨论】:

  • 谢谢@Willek。我曾尝试过类似的方法,但没有奏效,在 NSWindow 上执行它就像魅力一样。
  • 请注意,解决方案 A 有一个潜在的错误,即使在触发设置第一响应者的鼠标事件期间,它也会自动滚动。您可以通过在函数的第一行后添加以下内容来防止这种情况:NSEventType currentEventType = NSApp.currentEvent.type; BOOL isKeyboardEvent = currentEventType == NSEventTypeKeyUp || currentEventType == NSEventTypeKeyDown; if (!isKeyboardEvent) { return madeFirstResponder; }
  • @LironYahdav 为什么这是一个错误?我怎样才能重现这个错误?方案B也有这个bug吗?
  • 如果您有任何鼠标事件处理程序调用 makeFirstResponder 您可以重现该错误。我猜 B 会有同样的错误。
  • 我将其称为功能(将焦点自动滚动到视图中)而不是错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多