Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a parameter to the action of Button with SwiftUI

Tags:

button

swiftui

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?

like image 262
ARR Avatar asked Dec 31 '22 09:12

ARR


2 Answers

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())
}
like image 63
ARR Avatar answered Apr 26 '23 18:04

ARR


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)")
    }
}
like image 34
dlavapad Avatar answered Apr 26 '23 18:04

dlavapad