Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

swift - List all Locale Identifiers and corresponding region text Swiftui

I would like to generate a list of all Locale identifiers for the user to select as a default. Similar to selecting the region in the standard settings.

Thus I would like to generate a list that would contain e.g. "Australia", "Austria", "Azerbaijan", ... ,"Yemen", "Zambia", "Zimbabwe". If the user selects "Australia" I would like to return en_AU.

So need to identify the property under Locale that can be used and how to iterate through it.

Currently, just trying to see if I can return the text e.g. "Australia":

Text(Locale.localizedString(Locale.init(identifier: Locale.availableIdentifiers[0].description)))

However returning error:

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

Thank you

question from:https://stackoverflow.com/questions/65517241/list-all-locale-identifiers-and-corresponding-region-text-swiftui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Seems like you are looking for the name of each identifier. You can get those from the NSLocale like:

Locale.availableIdentifiers.map {
    (id: $0, name: (NSLocale.current as NSLocale).displayName(forKey: .languageCode, value: $0) ?? "-")
}

So you can rise them as you like. For example, showing them in a list:

struct ContentView: View {
    let localeSheet: [(id: String, name: String)] = {
        Locale.availableIdentifiers.map {
            (id: $0, name: (NSLocale.current as NSLocale).displayName(forKey: .languageCode, value: $0) ?? "-")
        }.sorted { $0.name < $1.name }
    }()

    var body: some View {
        List(localeSheet, id: .id) {
            Text($0.name)
            Spacer()
            Text($0.id)
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...