2

我正在向我的 SwiftUI 应用程序中添加可访问性,直到在 a中添加accessibilityLabel(_:)a时遇到问题。这是一些示例代码:ButtonToolbarItem

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            Text("Content")
                .accessibilityElement()
                .accessibilityLabel("Content label") // This is here just to show Voice Control is working
                .navigationTitle("Test")
                .toolbar {
                    // Comment parts out below, depending on what you want to test
                    ToolbarItem(placement: .navigationBarTrailing) {
                        // What I want, but doesn't work:
                        // (Also tried adding the label to either the button
                        // label or the whole button itself, neither works.)
                        Button {
                            print("Pressed")
                        } label: {
                            Image(systemName: "plus")
                                .accessibilityElement()
                                .accessibilityLabel("Some label")
                        }
                        .accessibilityElement()
                        .accessibilityLabel("Some other label")
                        
                        // What I don't want, but does work:
                        Image(systemName: "plus")
                            .accessibilityLabel("Another label")
                    }
                }
        }
    }
}

我正在使用Voice Control测试可访问性。奇怪的是,可访问性标签适用于工具栏项目中的图像,但不适用于工具栏项目中的按钮内。

当我说可访问性标签不起作用时,它会说"Add"而不是预期的标签。我假设 SwiftUI 默认为系统映像“加号”创建此标签,但我想更改它。

当不在工具栏项目中时,按钮可访问性标签也可以工作。这是一个错误,还是我造成的一些问题?

4

2 回答 2

4

SwiftUI 以不同的方式处理单个工具栏项(应用它们自己的样式、大小等)。看起来这也适用于可访问性标签。

幸运的是,有一种解决方法 - 请参阅SwiftUI Xcode 12.3 can't change button size in toolbar

在您的情况下,代码应如下所示:

.toolbar {
    ToolbarItem(placement: .navigationBarTrailing) {
        HStack {
            Text("")
                .accessibilityHidden(true)
            
            Button {
                print("Pressed")
            } label: {
                Image(systemName: "plus")
                    .accessibilityElement()
                    .accessibilityLabel("Some label")
            }
        }
    }
}

accessibilityLabel可以附加到ImageButton。)

使用 Xcode 12.3、iOS 14.3 测试。

于 2021-01-19T12:56:18.857 回答
2

更新:iOS 15+ 已修复此问题。

我的雷达有“少于 10 个”类似的报告,但现在实际上已针对 iOS 15+ 修复。但是,如果您支持旧版本,请参阅上面@pawello2222 的答案,这是一个更新版本,仅在必要时执行解决方法:

/// Embeds the content in a view which removes some
/// default styling in toolbars, so accessibility works.
/// - Returns: Embedded content.
@ViewBuilder func embedToolbarContent() -> some View {
    if #available(iOS 15, *) {
        self
    } else {
        HStack(spacing: 0) {
            Text("")
                .frame(width: 0, height: 0)
                .accessibilityHidden(true)

            self
        }
    }
}

于 2021-07-21T03:07:16.400 回答