Accessibility text for SwiftUI button action

369 Views Asked by At

I have a use case where I wanted to have different text for VoiceOver after SwiftUI button click.

Initial value is different and it can be set with accessibilityLabel or accessibilityValue for e.g. "Tap here to increment the count"

Button {
  // button action
} label: { 
  Text("Increment") 
} 
.accessibilityValue("Tap here to increment the count") 

but how can I set a new value with button action, voice over should be calling count for e.g. "Count is 10"

can someone please suggest, which property should I use here

Note* after button click I need only action text voice out and it should be without the initial text

1

There are 1 best solutions below

0
Pierre Janineh On

To change the VoiceOver text after a SwiftUI button click, you can use a state variable to dynamically update the accessibilityLabel of the button.

When the button is tapped, you can update this state variable, which in turn will update the accessibility text read by VoiceOver.

Here's a basic example to demonstrate this:

import SwiftUI

struct ContentView: View {
    @State private var count = 0
    @State private var voiceOverText = "Tap here to increment the count"

    var body: some View {
        Button(action: {
            count += 1
            voiceOverText = "Count is \(count)"
        }) {
            Text("Increment")
        }
        .accessibilityLabel(Text(voiceOverText))
    }
}