gpt4 book ai didi

ios - ForEach 两个数组 - 简单的解决方案可能吗?

转载 作者:行者123 更新时间:2023-12-04 07:58:44 25 4
gpt4 key购买 nike

我正在努力寻找一个我找不到的简单解决方案。我想构建一个显示标志并从另一个数组中选择语言代码的选择器。必须有一个简单的解决方案。这么久了,我帮助自己解决了这个丑陋的问题 onChange拐杖。
有什么建议?

struct LanguageView: View {

@AppStorage ("language")var language: String = "de"
@State private var flag: String = ""
var languages = ["de", "en", "pl"]
var languageFlags = ["🇩🇪", "🇬🇧 🇺🇸", "🇵🇱" ]

var body: some View {

VStack{

HStack{

Picker("", selection: $flag) {
ForEach(languageFlags, id: \.self) {
Text($0)
.font(.caption2)
}

}
.pickerStyle(SegmentedPickerStyle())

}.onChange(of: flag, perform: { value in
if flag == "🇩🇪" {language = "de"}
if flag == "🇬🇧 🇺🇸" {language = "en"}
if flag == "🇵🇱" {language = "pl"}
})
}

.environment(\.locale, .init(identifier: language))
}
}

最佳答案

我认为这也可以很好地满足您的需求,您应该像我一样定义自定义类型!用我的代码,选择的语言直接保存,你不用担心!我会说更安全。

import SwiftUI

struct ContentView: View {
var body: some View {
LanguageView()
}
}
struct Language: Hashable {
let language: String
let flag: String
}
let languageArray: [Language] = [Language(language: "de", flag: "🇩🇪"), Language(language: "en", flag: "🇬🇧 🇺🇸"), Language(language: "pl", flag: "🇵🇱")]
struct LanguageView: View {
@AppStorage ("language")var selectedFlag: Int = 0
var body: some View {
VStack{
HStack{
Picker("", selection: $selectedFlag) {
ForEach(languageArray.indices, id: \.self) { index in
Text(languageArray[index].flag)
.font(.caption2)
}
}
.pickerStyle(SegmentedPickerStyle())
}
.onAppear() { print("language is: " + languageArray[selectedFlag].language) }
.onChange(of: selectedFlag) { newValue in
print("language is: " + languageArray[newValue].language)
}
}
}
}

关于ios - ForEach 两个数组 - 简单的解决方案可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66571706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com