Implementing a language selection feature in Swift (UIKit)
A language selection feature implemented in Swift(UIKit) with “Bundle.setLanguage(langCode)” only changes the language on the page where the code is written and on the Segue targets made from that page with Storyboard.
The code “Bundle.setLanguage(langCode)” actually changes the system language. This means that if you close and reopen the application after this code is executed, the language will change on all pages. However, we want the language to change on all pages without closing the application.
The problem here is page changes made outside of segues. For example, you can look at the code below. When this code is executed, it will navigate to the page with the ID “newPage”. However, the page will appear with the new page language unchanged.
We also add the line “Bundle.setLanguage(langCode)” to the page change code. The code above can be used to change pages in many different classes. We save the selected language to “Userdefaults” on the language selection page. This allows us to access the “langCode” in the page change functions found in other classes, so that we can use the “Bundle.setLanguage” code to change the language of the new page.
In the following code, we also retrieve the “langCode” that we saved to Userdefaults. Then, we use the “Bundle.setLanguage(langCode)” code to change the language of the next page just before changing the page.
In this article, we saw how to implement a language selection feature in Swift(UIKit). By using this code, you can customize your app’s language to suit your users’ preferences.
The key steps we covered in this article were:
- Create a language selection page.
- Prompt the user to select a language.
- Set the selected language as the app’s language.
By following these steps, you can easily create a similar language selection feature for your own app.
We hope this article was helpful. If you have any questions or suggestions, please feel free to leave a comment.
Goodbye!
Contact: info@ozancicek.dev