4

Problem:

I'd like to use accessibilityIdentifier() in SwiftUI on iOS 14, but some of the code supports iOS 13+.

Can I keep using the same API as the iOS 14+ version which will do nothing on iOS 13?

e.g.:

/// How to make this available on pre-iOS 14 only?
extension View {
    func accessibilityIdentifier(_ identifier: String) -> some View {
        if #available(iOS 14.0, macOS 11.0, *) {
                .accessibilityIdentifier(identifier)
        } else {
            self
        }
    }
}

Richard Topchii
  • 7,075
  • 8
  • 48
  • 115

1 Answers1

2

A possible approach is to create own wrapper, like (tested with Xcode 13.2)

extension View {
    @ViewBuilder
    func accessibility(id identifier: String) -> some View {
        if #available(iOS 14.0, macOS 11.0, *) {
            self.accessibilityIdentifier(identifier)
        } else {
            self.accessibility(identifier: identifier)
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Yeah, but this won't match 1:1 with the original API. Any way to make it match, so that at a later stage I'll just remove it completely (after bumping up the minimum required version) – Richard Topchii Mar 28 '22 at 09:08
  • You cannot use function with same signature in call, you will just cycle. There is no *override* here it is not OOP part, no super. That's why needed new function signature to wrap those condition. – Asperi Mar 28 '22 at 09:35
  • Can I use this `ViewModifier` instead and call it there? https://stackoverflow.com/questions/70285885/swiftui-use-accessibilityidentifier-only-on-ios-14 So that I won't cycle back to the same function? Also, can I segregate those two functions by module, e.g. `SwiftUI.View.accessibilityIdentifier` or something similar? – Richard Topchii Mar 28 '22 at 09:42