Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI: use 'accessibilityIdentifier' only on iOS 14+

Given the following code:

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)
    }
}

I’m getting the following error:

‘accessibilityIdentifier’ is only available in iOS 14.0 or newer use
on iOS 14

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When looking at the accessibilityIdentifier declaration, I found this:

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

Xcode suggest enclosing either the whole button style struct or at least the makeBody function to make it available on iOS 14+.

Is there a way to create an additional function, e.g.:

func addAccessibilityIdentifierIfAvailable(entryParam ??) -> some View

or similar that will return just the same view if the accessibilityIdentifier is not available or return a view with the set identifier if it’s possible to set on that OS version.

>Solution :

Here is a simple way for you:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading