selection
が index の値になってしまいます。
struct MyView: View {
@State var selection = 10
let items = [10,20,30]
var body: some View {
VStack {
Text("selection: \(selection)")
Picker(selection: $selection, label: Text("")) {
ForEach(0..<items.count, id: \.self) { index in
Text("\(items[index])")
.tag(items[index])
}
}
}
}
}
下の様に、Identifiable
なものをForEach
すれば直りました。
struct MyView: View {
@State var selection = 10
struct Item: Identifiable {
var id = UUID()
var num:Int
init(_ num: Int) { self.num = num }
}
let items = [Item(10), Item(20), Item(30)]
var body: some View {
VStack {
Text("selection: \(selection)")
Picker(selection: $selection, label: Text("")) {
ForEach(items) { item in
Text("\(item.num)")
.tag(item.num)
}
}
}
}
}
バージョン
Swift 5.4