Open up the starter project and run the app on a physical device, since the capabilities we need are not supported yet on the simulator.
Try tapping on any list item to see reviews of the cafes in the detail view.
Some cafes have reviews written by non-English reviewers. One of them is Humble Bakery. Tap Humble Bakery from the cafe review list to see reviews and highlights for that cafe.
You’ll notice the review for Humble Bakery isn’t in English, but there’s a Translate button! You might be keen to tap that button and try to translate, but when you do, nothing happens.
Fret not! Displaying the basic text overlay to translate a specific part of your UI is one of the easiest ways to use the Translation API.
Here’s a step-by-step guide:
First, open DetailView and import the Translation framework:
import Translation
Then add this State property wrapper within the DetailView struct:
@State private var showTranslation = false
We use this variable to show or hide the translation text overlay. To achieve this we call toggle on our showTranslation variable when the Translate button is tapped:
Button("Translate") {
showTranslation.toggle()
}
Finally, append the translationPresentation modifier at the end of your VStack:
.translationPresentation(isPresented: $showTranslation,
text: translatableText)
This modifier takes two parameters:
-
isPresented is a
Boolto change the visibility of the translation overlay. -
text is the
Stringfor the text to translate.
Build and run.
Select Humble Bakery from the Cafe Reviews screen again.
The DetailView opens with the selected cafe review. Tap the Translate button to display the on-screen overlay and translate the cafe review from Italian to your preferred language!