I would like to change the language in my app, in order to do that I want to use Buttons. So for each language I will have a Button, which will pass a parameter with the language code of that language.
Now I know it is possible to pass a function to a Button but how to pass a function with a Parameter?
To pass parameters to the action, I think there are multiple ways to do so. But I found this the most elegant way of doing it.
First of all I create a function which accepts a parameter "language". Then that function will return an anonymous function which uses the "language" parameter:
func changeLanguage(language: String) -> () -> () {
return {
print(language)
}
}
In the view I can create Buttons which will hold the anonymous function which is being returned by "changeLanguage" with a "language" parameter that can differ per Button.
var body: some View {
List {
Section(header: Text(NSLocalizedString("Language", comment: "settings.view.select.language"))) {
Button(NSLocalizedString("English", comment: "settings.view.language.english"), action: self.changeLanguage(language: "en"))
Button(NSLocalizedString("Dutch", comment: "settings.view.language.dutch"), action: self.changeLanguage(language: "nl"))
}
}
.listStyle(GroupedListStyle())
}
You can use a closure calling a method with your parameter, like this:
import SwiftUI
struct LanguageView: View {
var body: some View {
Button(action: { selectLanguage(language: "en") }) {
Text("English")
}
}
func selectLanguage(language: String) {
print("Language selected: \(language)")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With