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
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.
CodePudding user response:
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 }
}
}
CodePudding user response:
One of the solutions:
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
}
}
}
Call site:
Text("")
.modifier(AccessibilityIdentifier("text123"))