简体   繁体   中英

How to pass a parameter to the action of Button with 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?

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)")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM