【问题标题】:SwiftUI: use 'accessibilityIdentifier' only on iOS 14+SwiftUI:仅在 iOS 14+ 上使用“accessibilityIdentifier”
【发布时间】:2021-12-09 07:06:06
【问题描述】:

给定以下代码:

struct CopyButtonStyle: ButtonStyle {

    init() {}

    func makeBody(configuration: Configuration) -> some View {
        let copyIconSize: CGFloat = 24
        return Image(systemName: "doc.on.doc")
            .renderingMode(.template)
            .resizable()
            .frame(width: copyIconSize, height: copyIconSize)
            .accessibilityIdentifier("copy_button")
            .opacity(configuration.isPressed ? 0.5 : 1)
    }
}

我收到以下错误:

'accessibilityIdentifier' 仅在 iOS 14.0 或更新版本中可用 在 iOS 14 上

查看accessibilityIdentifier 声明时,我发现:

public func accessibilityIdentifier(_ identifier: String) -> ModifiedContent<Self, AccessibilityAttachmentModifier>

Xcode 建议包含整个按钮样式结构或至少 makeBody 函数以使其在 iOS 14+ 上可用。

有没有办法创建附加功能,例如:

func addAccessibilityIdentifierIfAvailable(entryParam ??) -> some View

如果accessibilityIdentifier 不可用或类似的,将返回相同的视图,如果可以在该操作系统版本上设置,则返回具有设置标识符的视图。

【问题讨论】:

标签: ios swift swiftui


【解决方案1】:

这里有一个简单的方法:

extension View {
   @ViewBuilder func addAccessibilityIdentifierIfVersionAvailable(identifier: String) -> some View {
        if #available(iOS 14.0, *) { self.accessibilityIdentifier(identifier) }
        else { self } 
    }
}

【讨论】:

    【解决方案2】:

    解决方案之一:

    import SwiftUI
    
    /// Adds AccessibilityIdentifier if it's available with the current
    /// version of the SwiftUI runtime, returns the same view otherwise
    struct AccessibilityIdentifier: ViewModifier {
        private let identifier: String
    
        /// Adds AccessibilityIdentifier if it's available with the current
        /// version of the SwiftUI runtime, returns the same view otherwise
        /// - Parameter identifier: accessibility identifier, similar to the standard SwiftUI `accessibilityIdentifier`
        init(_ identifier: String) {
            self.identifier = identifier
        }
    
        @ViewBuilder
        func body(content: Content) -> some View {
            if #available(iOS 14.0, macOS 11.0, *) {
                content
                    .accessibilityIdentifier(identifier)
            } else {
                content
            }
        }
    }
    

    调用站点:

    Text("")
    .modifier(AccessibilityIdentifier("text123"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多